Although Germany were far from their best, an 84th-minute equaliser from Leon Goretzka sealed a 2-2 draw against Hungary and a spot in the Last 16.
Hungary's valiant efforts went in vain as they finished fourth in Group E with just two points, however, they led for a major part of the game.
Captain Adam Szalai gave Hungary a shock early lead and although Germany drew level through Kai Havertz in the second half, the Hungarians went back in front almost immediately through Andras Schaefer.
With six minutes left, Goretzka fired home a crucial equaliser to set up a blockbuster tie against England at Wembley on Tuesday, eliminating Hungary who finished bottom of Group F.
The match build-up had been dominated by UEFA's refusal to allow the city of Munich to light the Allianz Arena in rainbow colours in solidarity with Hungary's LGBTIQ community.
UEFA and the government of Hungary came under a hail of criticism after Budapest's new anti-LGBTIQ law and the football body's refusal to light the Munich stadium.
Germany got off to a rough start when Szalai ghosted in between centre-backs Mats Hummels and Matthias Ginter to head Roland Sallai's superb cross past Manuel Neuer.
Delighted travelling Hungarian fans celebrated wildly as their German counterparts looked on in silence.
Hungary taking the lead with just 11 minutes gone sparked Germany into action as Hummels hit the crossbar, then Ginter fired straight at visiting goalkeeper Peter Gulacsi.
A cloudburst over north Munich soaked the Allianz Arena pitch as Germany poured forward in a desperate search for an equaliser.
The euphoria felt across the country after Germany's spectacular 4-2 win over Portugal just four days previously had suddenly evaporated.
But the hosts drew level on 66 minutes when Gulacsi failed to catch a Joshua Kimmich free-kick, Hummels headed the ball on and Havertz nodded into an empty net.
The joy in the German ranks was short-lived as Hungary regained the lead straight from the restart.
A long ball found Szalai, who lofted a pass over the defence where Schaefer got between the scrambling German defenders to head past an onrushing Neuer.
The crucial second German equaliser was down to two substitutes.
Teenager Jamal Musiala's cutback found his Bayern Munich team-mate Goretzka, who set up Timo Werner for a blocked shot.
But the rebound dropped to Goretzka who smashed the ball into the back of the net to avoid a humiliating group-stage exit.