Los Blancos had wasted a plethora of chances and were nearly punished for their wastefulness when Nabil El Zhar put the hosts ahead in the 86th minute.
© Getty Images
In an evenly contested first half, it was the visitors who finished the stronger, with Luca Modric and Isco both having good chances to break the deadlock.
The home side drew first blood after the break, as Papa Babacar Diawara placed the ball into the net for his first goal of the season in the 57th minute, but their defending was lax in conceding the equaliser.
A routine set piece ended with Ramos stealing in at the back post to force home Angel di Maria's deep cross.
The Argentine missed a glorious chance to put Real ahead in the 69th minute, before Marcelo squandered another five minutes later.
When former Liverpool man El Zhar finished well inside the area, it looked as if Real would be conceding yet more ground to La Liga leaders Barcelona, but Morata turned and shot past Keylor Navas in the last minute.
The visitors sensed blood and went all out for the win, and their risk was rewarded when Ronaldo's effort took a deflection on its way into the net.