In another match, Belgium eked out a hard-fought 1-0 win against Russia to enter the last-16 from group H.
Algeria beat South Korea 4-2 in another high-scoring thriller to keep their chances of knock-out qualification alive from Group H.
Portugal will now need to win big against Ghana in their last group league game while praying that another group G match between United States and Germany doesn't end in a draw, in order to qualify for the Round of 16.
It was Portugal captain Cristiano Ronaldo, who essayed the perfect centre for Varela to head home with just 30 seconds left for the final whistle.
More From This Section
It was one of the most exciting matches in which Portugal got the lead as early as in the fifth minute when Nani capitalised on a defensive blooper from Geoff Cameron.
A faulty clearance landed on Nani's feet as the Manchester United player slotted home from close range.
The injury to Postiga and the subsequent introduction of forward Eder did hurt Portugal. Eder failed to make any impact and lost a lot of balls in the opposition box much to the dismay of his captain.
Portuguese goalkeeper Beto was nowhere near and Bradley couldn't believe that Costa had pulled off that save.
However Jermaine Jones' swinging long-ranger from outside the penalty box saw a helpless Beto stranded as it rammed into the net. Jones received the ball when Nani's ill-directed feeble clearance came to him.
Skipper Clint Dempsey made it 2-1 in the 81st minute.
Yedlin made a lovely run along the right before cutting it back for Bradley. His shot was blocked into the feet of Zusi who crossed it for Dempsey. Dempsey chested it from close range to give US the lead.