Three days after Zinedine Zidane's side performed a great escape by coming from 2-0 down to defeat Villarreal, they produced a similar trick again.
But this result was even more extraordinary because Real played much of the second half with 10 men and were 3-1 behind until the 86th minute.
After Bale was sent off for an out-of-character shove, Las Palmas took advantage of the shell-shocked home side when Viera fired in from the spot after Ramos had handled David Simon's drive inside the area.
The Gran Canaria club, who had only managed one away win in La Liga this campaign, then added a third soon after when ex-Tottenham player Boateng beat keeper Keylor Navas to the ball to slot in.
Time was running out for Real, but they struck lucky in the 86th minute.
A firm cross from substitute James Rodriguez struck the hand of Dani Castellano. It appeared that the Las Palmas midfielder did not have time to move his hands away, but after short deliberation referee Fernandez Borbalan awarded a penalty. Ronaldo fired in from the spot.
With seconds of the match remaining, the Portugal forward, who appeared frustrated during the night, rose brilliantly to head in Rodriguez's cross.
Red mist descends on Bale
It was an unexpected flashpoint.
Bale began the match well, setting up Alvaro Morata in the first 30 seconds to tuck home, only for the effort to be ruled out for offside.
But in the 47th minute the night took a turn for the worse for the Wales international, who only recently returned from three months out with an ankle injury.
He twice clipped the heels of Viera before the Las Palmas player reacted. Referee Borbalan was set to show Bale a yellow card before the 27-year-old aggressively shoved Viera which prompted the official to show a straight red.
His suspension will be a blow for Real, with the forward having scored two goals since his comeback.