The result puts the group up for grabs with France on four points, Germany and Portugal on three and Hungary sitting last with a single point, but still with a slight chance to advance.
Story of the match
Germany had thought they had taken a fifth-minute lead after a cross by Matthias Ginter was stretched for and missed by Serge Gnabry before Gosens finished, only to see the goal disallowed for offsides on Gnabry.
Portugal was off the mark soon after a corner by Toni Kroos was cleared and Bernardo Silva sent a diagonal pass to Jota and after controlling with his chest, he found Ronaldo on the right and he tapped home past Manuel Neuer.
After Havertz and Kroos came close, Die Mannschaft were level when Gosens volleyed across goal and Dias deflected the ball past Rui Patricio. It happened again four minutes later after Kimmich retrieved the ball on the byline and Guerreiro sent the cut-back into his own net.
Slick passing resulted in Germany's third on 51 minutes as Thomas Muller found an open Gosens and although he slipped while crossing, Havertz converted on the run to double the lead to 3-1.
On the hour mark, Gosens was rewarded with a goal of his own when Kimmich crossed from his right and he converted with a powerful header to put the game out of reach.
Ronaldo set up Portugal's second in the 67th minute when he strained to keep alive a free-kick and Jota finished to cut the lead to 4-2. Renato Sanches sent German nerves jangling when he hit the post in the 73rd minute.
Man of the Match: Roben Gosens
It was a sensational overall performance by the wing-back, setting up his teammates time and time again with inviting crosses, delicious passes and his pace, creativity and energy spurred Germany on to victory. The goal was a richly deserved reward for his work on the night.
Ronaldo gets the record, but little help
The goal was his 19th in major tournament play, ironically tying Germany's legendary Miroslav Klose for the most all-time. The issue was he got no support as his defense was shambolic and aside from Jota, there was little offered in the way of service or help. For as good as the champions looked against Hungary, they were the exact opposite here.
Germany show character
It's no secret that since the night of their last major trophy, the 2014 World Cup, Die Mannschaft have been in a slide. Their failure to get out of the group stages of the 2018 World Cup was seen as rock-bottom and a defeat to France offered little reason to think anything would change.
Today's match signaled that perhaps a revival is in store. Facing long odds despite being at home, Germany showed that they shouldn't be given up on just yet, especially the way they responded after falling behind. The road back to glory may be long, but today was a start.