He powered home a low shot from outside the penalty area two minutes into the second half to bundle Nigeria out of the tournament.
Nigeria had been the only side to win all three of their games in the group phase and were overwhelming favourites as Tunisia battled without seven players, who were isolating because of COVID-19.
But Tunisia, who also had to do without coach Mondher Kebaier because of COVID-19, advanced to meet Burkina Faso in next Saturday's quarterfinal in Garoua.
There were few chances in the game with Tunisia producing a stout defensive performance and looking for counter attacking opportunities.
They were reduced to 10 men when Alex Iwobi was sent off for a dangerous tackle in the 66th minute, seven minutes after coming on.
The referee originally handed him a caution, but was encouraged to review the sanction on the pitchside VAR screen before changing his mind and sending Iwobi off.
The 31-year-old Msakni, competing in his seventh Cup of Nations finals but starting his first match of the tournament, was given time to line up his shot and it swerved to catch out the Nigeria goalkeeper Maduka Okoye, who only managed to get a hand to it.
"We got punished for one mistake," said Nigeria coach Augustine Eguavoen. "Alex should not have been given a red card but the referee saw it differently. But congratulations to Tunisia."
It was a remarkable turnaround for the north Africans, who had lost two of their three opening round games, including an embarrassing 1-0 defeat to tiny Gambia three days ago.
They managed to get some players back out of isolation ahead of Sunday's match but assistant coach Jalel Kadri had to take over for the game.
Nigeria threw players forward near the end and substitute Umar Sadiq might well have forced a stoppage-time equaliser but his effort went agonisingly wide of the goal.