Defending a 2-1 lead from the first half, Madrid were taken into extra time by the German side, who had midfielder Nacho Vidal unjustly sent off in the closing minutes over normal time, while Madrid's midfielder Casemiro could have seen his second yellow card of the night on two separate occasions, only to be pardoned by the referee on both occasions.
Meanwhile Cristiano Ronaldo's second goal of the night, which gave Real Madrid a 3-2 advantage in the tie was scored from a clear offside position.
With a 10-man Bayern then chasing the game in the closing minutes of extra-time, further goals from Ronaldo and Marco Asensio sealed the tie.
The first half was a high-octane affair with both sides looking for an early goal, but despite both sides playing at 100 percent, and Marcelo twice in a minute saved Madrid with blocks from efforts from Arjen Robben and Thiago Alcantara.
At the other end Tony Kroos fired just wide, while Ronaldo took his time in the area to allow Manuel Neuer to make the save.
The halftime break saw incidents in the stand as the Spanish police launched a series of baton charges against Bayern fans and the game caught fire on in the second half when Bayern took the lead after Casemiro, who had already been booked, scored a penalty against Robben and Robert Levandowski.
Bayern pushed hard for a second goal which would have put them into the last 4, but Ronaldo leveled the score on the night with 15 minutes remaining following a Casemiro cross.
Two minutes later a Sergio Ramos own goal tied the aggregate score as he somehow put the ball into his own net with Keylor Navas helpless, but before the end of normal time Bayern were reduced to 10 men after Arturo Vidal was sent off for a second yellow card following a challenge on Marco Asensio in which he clearly won the ball.
Bayern tried hard in extra time, but the extra man was a key factor and Ronaldo made it 2-2 on the night in the 105th minute, after receiving the ball in an offside positon.
With the German side needing to score twice, Ronaldo finished his hat-trick and Asensio also scored as Madrid twice caught a Bayern side on the break.