The Champions League winners had been without a boss since Zinedine Zidane revealed that he was stepping down from his role last month, but the Spanish giants have acted quickly to secure the Frenchman's replacement.
Lopetegui is currently preparing to lead Spain at the World Cup, but the 51-year-old will depart his role as national team coach at the end of the tournament.
A club statement said: "Real Madrid CF. announce that Julen Lopetegui will be the coach of the first team during the next three seasons.
"Julen Lopetegui will join the club after Spain's participation in the World Cup, after two years leading the national team."
Lopetegui has put together a record of 14 wins and six draws from his 20 games in charge of Spain, with the former goalkeeper having previously coached at Under-19, Under-20 and Under-21 levels.
The ex-Porto manager is also no stranger to Real, with three years spent at the Bernabeu between 1988 and 1991 during his playing days and a period coming in charge of Real's 'B' squad between 2008 and 2009.