The European champions led 1-0 from the quarter-final first leg.
Javier Eraso levelled the scores on aggregate before Karim Benzema restored Real’s aggregate lead.
Brazilian midfielder Gabriel hit Leganes’ winner as the visitors advanced to the semi-finals on the away goals rule.
Real were without both Cristiano Ronaldo and Gareth Bale for the game against their near neighbours, who were playing in the third tier of Spanish football four years ago.
Yet Zinedine Zidane’s side still included established players including defender Sergio Ramos, midfielder Isco and striker Benzema.
The Real boss is expected to come under renewed pressure after yet another defeat.
The 19-time Copa del Rey winners have lost four La Liga games this season and trail leaders Barcelona by 19 points.
Their last realistic hope of silverware this season rests with the Champions League.
The 12-time European champions face a tough tie with Paris St-Germain in the last 16, with the first leg in Madrid on 14 February.
This will go down as a famous night for Leganes, who lie 13th in La Liga.
They had lost all five of their previous league and cup games with Real.