It was a much-needed victory for Germany — which had lost its opening game against France earlier this week — and a clinical attacking display, putting Joachim Low’s side level on points with Portugal in Group F.
In the highest-scoring game of the tournament so far, Cristiano Ronaldo gave defending champion Portugal an early lead when he finished off a flowing counter-attack.
Ronaldo started the move himself when he headed the ball clear from a corner to launch a Portugal break through Bernardo Silva.
Silva then lifted the ball to Diogo Jota, who crossed to Ronaldo for a simple finish having sprinted the length of the pitch. It was the 36-year-old’s 107th international goal, moving him two behind the all-time record held by Iran’s Ali Daei.
However, Germany hit back and led by halftime after Ruben Dias and Raphael Guerreiro each scored own goals in the space of four minutes as they struggled to deal with dangerous crosses into the box.
Germany extended its lead at the start of the second half when a well-worked move saw Gosens find space in the Portugal box. He picked out Havertz with a cross and the Chelsea forward tapped in from close range.
Gosens then got a goal himself on the hour mark when he headed in Joshua Kimmich’s perfectly placed cross at the back post, and suddenly Germany had opened up a commanding 4-1 lead.
It lasted seven minutes as Portugal pulled one back when Ronaldo knocked a free kick back across goal for Jota to smash in from close range.
Both sides continued to attack in the closing stages and Portugal almost got a third when Renato Sanches thundered a shot against the post.
But Germany, which had looked assured throughout, saw out the game to complete a well-deserved victory ahead of its final group stage game against Hungary.
In the group’s other game, world champion France was held to a 1-1 draw by Hungary.
Attila Fiola’s goal just before halftime gave Hungary an unlikely lead in Budapest, sparking wild celebrations inside a packed Puskas Arena.
But France, which dominated most of the game, equalized after an hour when goalkeeper Hugo Lloris’ long pass found Kylian Mbappe, whose deflected cross was finished by Antoine Griezmann.
France stays top of the group on four points before facing Portugal on Wednesday.