Diego Costa slammed home a 77th-minute penalty to take all three points for Diego Simeone's side, who had gone behind with less than two minutes on the clock and then conceded a second-half equaliser shortly after taking the lead.
Andreas Ivanschitz stunned the Vicente Calderon with an early goal for the visitors, which was eventually cancelled out by a Diego Godin header.
Costa put the hosts ahead two minutes into the second half but Pedro Rios' solo effort on 57 minutes meant Los Rojiblancos required one more goal, which they finally got when Costa fired into the bottom corner from the spot.
Sevilla continued their excellent recent run of form by beating Villarreal 2-0 away from home to move up to seventh.
Unai Emery's side's plan was to frustrate their hosts and it worked perfectly. Juan Cala headed the visitors into the lead in the 24th minute from a set piece, and with 19 minutes remaining Carlos Bacca made sure of the points by taking advantage of a defensive error.
Villarreal had been far from their best but were awarded a penalty late on when Jaume Costa was fouled by Cala, and the defender was shown a straight card.
Down at the bottom end of the table Ramon Azeez's early score was enough for Almeria to claim a much-needed 1-0 victory over fellow strugglers Real Betis.
Azeez drilled a strike from 30 yards in only the third minute which beat the Betis defence in the only breakthrough of the game.
The result means Almeria climbed out of the bottom three and into 15th place while Betis remain rooted to the bottom of the overall standings.
In the late game a Carlos Vela brace saw Real Sociedad move into fifth in the table after a comfortable 3-1 victory over Granada at Los Carmenes.
The former Arsenal striker opened the scoring after 29 minutes before Francisco Piti equalised for the home side. Antoine Griezmann doubled Sociedad's score minutes ahead of half-time before Vela struck again midway through the second half.
The result leaves Lucas Alcaraz's men with just three points from their last four matches and 11th in the league standings.