Eibar defender Ivan Ramis had seemingly done enough to secure a point for the home side that would have left their visitors trailing second-placed Atletico Madrid by six points, but Ronaldo struck in the 84th minute to rescue the win and ensure Valencia cannot leap above them later on Saturday.
Before kick-off, Atletico Madrid and Barcelona had been the only two sides to leave Eibar with all three points since the end of October and Zinedine Zidane's side struggled to get to grips with their wingers during the early exchanges.
Eventually Madrid appeared to exert a degree of control and Ronaldo – following a moment of Luka Modric inspiration – opened the scoring in the 34th minute, continuing his brilliant recent form.
But Eibar secured themselves a deserved equaliser five minutes after the restart, as Ramis headed in a corner from Pedro Leon, who provided an assist against his former club for the sixth time, the most he has provided against any other opponent in LaLiga.
Luck appeared to have deserted Madrid after they wasted several chances, with Ronaldo among those guilty, but the Ballon d'Or holder produced an emphatic late header with his 17th goal in 10 games, moving them to within four points of Atletico, who face Celta Vigo on Sunday.
Madrid travelled to Ipurua knowing they were not going to be facing an Eibar side that is easily dominated.
And Eibar's start gave every indication that Zidane's men were in for a long day, as they troubled through Leon in the first minute – the former Madrid winger's cross nearly finding Kike Garcia.
Eibar appeared to target Madrid's full-backs and their crosses from both flanks continued to trouble, even if they often just missed the intended target.
Keylor Navas then had to be at his best in the 19th minute, tipping Kike's 20-yard effort just past the post.
Madrid – who lost Raphael Varane to a head injury – gained a foothold, though, with Gareth Bale forcing the approaching Marko Dmitrovic into action in the 32nd minute.
Shortly after, the visitors had the lead – Modric finding Ronaldo with a remarkable lofted pass using the outside of his foot and the forward finishing the chance with aplomb.
But Eibar once again looked an attacking threat upon the restart, with Navas called into action early on as he tipped Gonzalo Escalante's deep delivery over the crossbar.
And from the resulting corner, Ramis lost Sergio Ramos and headed beyond the helpless Navas to equalise.
Ronaldo seemed destined to restore their lead when Bale passed into the area just after the hour mark, but Dmitrovic produced a sensational save to deny him.
Eibar should have put themselves ahead 14 minutes from the end when Escalante nodded the ball to Takashi Inui and he headed well over from close range.
Ronaldo subsequently punished that miss, meeting Dani Carvajal's right-wing cross with a powerful header that gave Dmitrovic no chance and sent Madrid back to the capital victorious.