Australian Miller of Ducati-Pramac overtook but entering the last corner Espargaro was half a wheel ahead.
As the two forced each other wide, Oliveira on his independent KTM, dived through on the inside to win. Miller was second and Espargaro third.
“I was very surprised,” said Oliveira. “Because I crossed the finish line. I saw the chequered flag and no one was around me and I was like ‘I’m going to win’. It was sweet. Super cool.”
The race was interrupted when the brakes on Maverick Vinales’ Yamaha failed and he threw himself onto the tarmac before the riderless bike smashed through one of the safety barriers.
The interruption cost Suzuki’s Johan Mir who was leading but had no another front tyre available while other teams used the pause to change theirs.
Espargaro had been leading when the previous week’s Austrian Grand Prix was interrupted by a red flag.
After the restart, Miller and Espargaro broke clear. In the closing laps, Oliveira joined them. He took advantage as the leaders focused on each other on the final corners.
“I tried to brake a little early and ride underneath Pol,” said Miller “I didn’t expect Oliveira to be there”.
Espargaro acknowledged the restart had prevented Mir winning.
“It was not our race it was Mir’s race. He was the fastest,” said Espargaro.
Mir was fourth, while Oliveira made history.
“First for Portugal on 900th MotoGP,” said Oliveira. “We are the best. History for me today and for my country.”
Further back, South African rider Brad Binder held on to finish eighth on his KTM.
Frenchman Fabio Quartararo, who finished in 13th place, remained in the lead of the World Championship with a three-point advantage over Ducati’s Italian Andrea Dovizioso who was fifth on Sunday.