An attacking full back, Hakimi started all three of Morocco's games at the World Cup in Russia before they were eliminated in the group stage.
The 19-year-old Real Madrid academy graduate made nine league appearances for the Spanish club under Zinedine Zidane last season, as well as playing five times in the King's Cup and twice in the Champions League.
"Achraf Hakimi is a young, very dynamic full-back who has played at the very highest level with Real Madrid and the Morocco national team," Dortmund sporting director Michael Zorc said in a statement.
Hakimi is new manager Lucien Favre's latest acquisition in a busy close season following the arrival of goalkeepers Marwin Hitz and Eric Oelschlagel, midfielders Thomas Delaney and Marius Wolf and defender Abdou Diallo.
He will join the Dortmund squad during the U.S. pre-season tour between July 18-26.