Shakhtar thought they had held out, then had their hopes seemingly shattered as Federico Valverde scored an apparent equaliser in extra-time.
Zinedine Zidane's side were three goals down at half-time, before a sublime Modric strike sought to launch a comeback.
The Ukrainian champions arrived in Madrid without 13 first-team players after 19 positive COVID-19 tests throughout the club left them needing to call up youth-team players, according to the BBC.
Tete was again at the heart of the attack and his shot was this time saved by Real goalkeeper Thibault Courtois, only for Raphael Varane to poke the ball into his own net as he tried to make an awkward clearance.
It meant Madrid let in three first-half goals in the Champions League for the first time since September 2005, in a clash with Lyon.
There was one last twist, though, as the goal was ruled out for offside - a cruel end to a night to forget for Madrid ahead of El Clasico against Barcelona on Saturday.
For all the determination they showed to right a terrible start, Madrid's scorers were realistic about the quality of their performance. "We will have to be at our best to win".
Austrian champions Salzburg and their United States coach Jesse Marsch were on course for that until Lokomotiv substitute Vitali Lisakovich headed in at the far post to level the game on his Champions League debut.
"For the next game, we have to be together, trust in ourselves and in our quality".
"Nobody did things well and we couldn't do what the boss asked us to".
"We knew what difficulties we could expect and planned our strategy accordingly", he said.
Many had this down as the most intriguing tie of the first round of fixtures, with both of these teams among the favorites to reach the latter stages of this season's competition.
"I think Madrid underestimated us but we showed our football and our style", said Shakhtar's Korniienko.