The home side made a flying start and opened up a two-goal lead within the first five minutes thanks to Martin Stranzl and Mike Hanke.
Javi Martinez reduced arrears soon after but Harvard Nordtveit restored Gladbach's two-goal advantage in a frantic opening 10 minutes.
However, Ribery cut the deficit to 3-2 after 18 minutes and then hit an equaliser early in the second half, before setting up Arjen Robben's decisive goal on the hour.
The win sees Bayern finish the season on 91 points, the highest total in Bundesliga history and the perfect preparation for next weekend's Champions League showdown with Borussia Dortmund at Wembley.
However, they paid the price for a nervy start and were two goals down after just five minutes.
Stranzl headed home the opener after four minutes from Juan Arango's free-kick, and moments later Dante's pass was snatched up by Branimir Hrgota, who laid the ball off for Hanke to fire past Bayern goalkeeper Manuel Neuer.
Bayern pulled one back in the seventh minute on a counter-attack with Ribery playing the ball forward to Martinez, who beat Gladbach keeper Marc Andre ter Stegen at the right post.
However, Gladbach made it 3-1 three minutes later with Patrick Herrmann feeding Nordtveit, who got the better of Neuer before tucking the ball into the bottom left corner.
The goals kept coming at Borussia Park and Bayern struck again in the 18th minute with Ribery's shot going in off the inside of the left post.
The Frenchman then ensured the scores were level eight minutes into the second half with a stunning left-footed volley from 25 yards.
And Bayern finally grabbed the lead six minutes later with Ribery whipping a cross toward the right post, where Robben was waiting to volley in.
Gladbach keeper Ter Stegen ensured the champions could not add to their tally, making fine saves to deny David Alaba and Martinez.