The Brazilian picked up the ball on the left flank and cut inside past three defenders. He then played a one-two with Gonzalo Higuain, dodged two more Lokomotiv players and knocked the ball through goalkeeper Guilherme's legs.
Juventus' substitutes came onto the pitch to celebrate as Douglas Costa pulled off his shirt. It was his first goal of the season after a long absence with a muscle injury. "This was a really important game because I have been out for a long time but I have come back and helped the team," said Douglas Costa, who was a 70th-minute substitute.
The goal ensured Juventus qualified from Group D with two games to spare. With seven changes from Saturday's derby win over Torino, Juventus took the lead with its 300th Champions League goal in confusing circumstances in the fourth minute.
Cristiano Ronaldo curled in a free kick from the left flank and Lokomotiv goalkeeper Guilherme let the wet ball slip through his hands. As it rolled over the line, Aaron Ramsey poked it into the net. UEFA credited Ramsey as the scorer.
"I thought the keeper was a lot closer to me and had a chance of diving back and maybe clearing it," Ramsey said. "My instinct took over to make sure that it went over the line. I've apologized to Cristiano."
Juventus' lead lasted just eight minutes before Alexei Miranchuk leveled for Lokomotiv, knocking in the rebound after his header hit the post. Guilherme made a string of good saves to keep Lokomotiv in the game, making up for his earlier blunder before Douglas Costa scored the winner.
Bayer Leverkusen upset Atletico Madrid 2-1 in Wednesday's other game in the group, leaving Juventus with a three-point advantage over Atletico at the top of Group D. "We still have work to do to finish top but we achieved our target of qualifying tonight, so we're happy that we've done that," Ramsey said.
Leverkusen and Lokomotiv are likely fighting for third and a spot in the Europa League. They're level on three points.
More AP soccer: https://apnews.com/Soccer and https://twitter.com/AP_Sports