"With the ball we were always good, we defended well; they didn't have big chances until the goal at the end," Thibaut Courtois said after the game.
"We did have chances where we didn't have the final ball or the finish. Going ahead is good, then at the end we had to focus more. With two minutes left here with the crowd, anything can happen. But it's a very good win and important to stay up in the table.
"We played a medium block, we didn't want to drop too deep, maybe we did that a bit at the end. The boss wanted us to go long. When you're winning here you have to defend the result, that's important too, not to go crazy and go for the second or third. It's important to be organised and that's what we did today."
The sides were even for much of the game with chances at both ends but it was David Alaba who opened the scoring.
Barca had the chance to open the scoring before Alaba's strike when Sergino Dest, starting in a more advanced role, somehow blazed the ball over the bar from close range.
However, it was Madrid who made the most of their shots on goal with Alaba breaking the deadlock on 32 minutes.
Ancelotti's side countered after Memphis Depay was dispossessed. Vinicius Junior and Rodrygo were both involved in the build-up before the ball found its way to Alaba who struck it past Marc-Andre ter Stegen and into the top corner.
Madrid played a safe game in the second half, slowing down play and frustrating Barcelona. The tactic worked as Ronald Koeman's side were unable to find an opening.
Lucas Vazquez made the win safe with a close-range finish on 93 minutes after Madrid caught Barca on the counterattack.
Sergio Aguero pulled one back for Barcelona in the sixth minute of added time with a close-range finish and Dest assisting. The goal is his first for Barcelona.
The loss is Koeman's third El Clasico defeat in a row.