It looked to be heading in when Welshman Aaron Ramsey popped up and stabbed home from on the goal line, denying Ronaldo of an all-important goal.
To add to Ronaldo's frustrating evening, he missed the chance to break the record for scoring against the most clubs in the Champions League.
It was not to be Ronaldo's night as he was replaced with nine minutes to go, yet Costa stepped up to be the hero, weaving in off the left wing and finishing after a one-two with Gonzalo Higuain.
There was a certain outbreak by Cristiano Ronaldo fans on Twitter after the Portuguese talisman was substituted with many slamming Maurizio Sarri for his decision.
Aleksey Miranchuk handed the host side the equaliser in the 12th minutes to level the score sheet in balance and give Lokomotiv a sigh of relief from growing pressure from Juve's threatening attackline.
"I was already nervous about this at half time".
However, the match sawCristiano Ronaldoget angry after being substituted in the 82nd minute.
Ramsey's goal was his second for Juventus since joining from Arsenal on a free this summer. Douglas Costa snatched the victor deep inside stoppage time, after Aaron Ramsey grabbed the opener in the opening minutes of the first half.
Aleksey Miranchuk equalised for Lokomotiv Moscow before half-time, but Costa's late victor secured the Bianconeri's place in the knockout stages.
Juventus came out victorious from their UEFA Champions League group stage encounter against Lokomotiv Moscow.