Zinedine Zidane, who led the club to three successive Champions League titles, stepped down in May, saying the club needs “a different voice”.
Lopetegui previously managed Porto for two years, before taking over at the Spanish national team in July 2016.
The 51-year-old will take up the position after the World Cup, which begins on 14 June.
A former goalkeeper, Lopetegui made one senior appearance for Real Madrid but played 107 matches for Logrones.
Real finished third in La Liga last season, 17 points behind champions Barcelona.
Forward Gareth Bale previously said he would hold talks regarding his future at the club, while Cristiano Ronaldo also said he would make an announcement on his future.
Spain begin their World Cup campaign against Ronaldo’s Portugal on Friday in a match.
‘Absolutely Nobody Was Expecting it’
As recently as Monday, Spain’s top selling sports newspaper Marca ran a story which claimed that Mauricio Pochettino was still Real Madrid’s preferred option for the vacant managerial position, with Liverpool’s Jurgen Klopp and Chelsea’s Antonio Conte also in the frame and former players Michel and Michael Laudrup among the outsiders.
Among all those names, one was not mentioned – and had not been mentioned – since Zinedine Zidane’s abrupt departure: Julen Lopetegui.
That tells you just how much of a shock the news of the Spain boss’s Bernabeu appointment has been. Absolutely nobody was expecting it, and now there is fevered speculation about exactly why the news was broken three days before the national team’s World Cup opener against Portugal, rather than being kept under wraps until after the competition.
Whatever the reasoning behind the timing of the announcement, it’s a fascinating appointment for a man who has done very well at international level, winning the European under-21 title in 2013 and qualifying for this summer’s World Cup in impressive style, but who has minimal experience at club level and failed in his last domestic job with Porto.
Lopetegui’s strong relationship with Real’s Spain internationals like Sergio Ramos and Isco will ensure he receives a warm internal welcome, but he now faces even more pressure as he heads into a World Cup leading a team which was already burdened by very high expectations.