Malaga - who have been transformed since Qatari Sheikh Abdullah Al Thani invested in them - were looking comfortable after goals by Sergio Sanchez and Martin de Michelis put them ahead but Real roused themselves to gain a slight advantage ahead of the second leg in Malaga next week.
Three goals in 10 minutes in the second-half by German midfielder Sami Khedira, Argentinian striker Gonzalo Higuain and French strike partner Karim Benzema saw a first choice Real side edge to victory.
Both Malaga's goals came from headers before the half hour mark but the hosts fortunes were transformed when coach Jose Mourinho sent on Khedira, Mesut Ozil and Benzema at half-time.
Khedira reduced the deficit after surging through the defence and lofting the ball into the net in the 68th minute and Higuain took advantage of a defensive mix-up by levelling two minutes later.
The comeback was complete when Higuain found Benzema with a superb defence splitting pass in the 78th minute and the rejuvenated French international made no mistake.
Real could have extended their lead on several occasions after that, Cristiano Ronaldo scoring with the last kick of the match - a spectacular bicycle kick - but it was ruled out rightly for offside.
What the stars mean:
★ Poor ★ ★ Promising ★★★ Good ★★★★ Very good ★★★★★ Exceptional