Karim Benzema scored twice in between goals from Gareth Bale and Sergio Ramos to secure the three points, despite a scare when Guido Carrillo made it 1-1 when he fired a penalty past debutant goalkeeper Thibaut Courtois.
The victory puts Julen Lopetegui's side top of the table, two points above Celta Vigo, which stunned Atletico Madrid 2-0 at Balaidos.
Bale stretched his scoring run to seven consecutive league games 17 minutes in, volleying in Dani Carvajal's header from 12 yards out, although goalkeeper Ivan Cuellar should arguably have done better to keep it out.
Leganes went into the game having failed to win any of its 10 Madrid derbies in LaLiga, but it snatched an equaliser 24 minutes in when Carrillo swept home from the penalty spot after Casemiro tripped Javier Eraso.
The goal seemed to disrupt Madrid's rhythm, although it continued to have nearly 80 per cent of the possession, with Cuellar denying Benzema's volley in one of the few chances before half-time.
But Benzema put Los Blancos back ahead three minutes after the break with a well-aimed header, the goal eventually given after a VAR (video assistant referee) review overturned a foul awarded against the striker.
There was no doubt about Benzema's second as he collected Marcelo's pass, played a one-two with Luka Modric and rifled a shot into the bottom-left corner from the edge of the area.
Captain Ramos added a fourth from the penalty spot 66 minutes in to move the European champion on to nine points and send it into the international break in a positive mood.
Madrid returns from the international break for a tricky trip to San Mames to take on Athletic Bilbao on 16 September (AEST). Leganes hosts Villarreal the next day.