Franck Ribery gave Bayern the lead in the 17th minute of the semi-final first leg, but Germany midfielder Mesut Ozil levelled early in the second half.
Bayern dominated for large parts of the game and found a deserved winner in the last minute through the prolific Gomez, giving them a slender advantage to take to Spain next week.
Madrid had the better of the first 10 minutes, but all they could produce was a shot from Karim Benzema which Manuel Neuer tipped over the crossbar after Bastian Schweinsteiger uncharacteristically gave away possession in midfield.
Bayern responded and took the game to their visitors.
Ribery felt he should have had a penalty when he went to ground under a challenge from Sergio Ramos inside the area, however referee Howard Webb waved play on. But the France winger was soon celebrating as he rifled Bayern in front with a shot from 10 yards, which only just avoided Luiz Gustavo in an offside position.
The hosts were looking dangerous every time they came forward, and those attacks were becoming increasingly frequent, with Arjen Robben marauding down the right and Ribery causing confusion in the Madrid defence down the Bayern left.
But they failed to make their pressure count, with Gomez's shot turned behind by Iker Casillas just before the break.
And Madrid levelled on the counterattack eight minutes after the restart.
Cristiano Ronaldo looked to have wasted the chance when his tame effort, one-on-one with the keeper, was saved by Neuer but Benzema picked up the rebound and took the ball back into the area, playing it across goal to Ronaldo, whose clever pull-back gave Ozil a tap-in from a yard out.
Madrid were enjoying their best spell of the game and many of the 66,000 fans in the Allianz Arena were becoming increasingly anxious.
The Bavarians regrouped and soon got back on top of the game, though. Gomez spurned an excellent chance to put them back in front in the 71st minute when he lifted the ball over the bar from close range after being teed up unwittingly by Ramos. He then headed straight at Casillas as the hosts continued to be frustrated in their attempts to find another goal.
Two hopeful penalty claims were waved away by referee Webb as Bayern kept on pressing and their pressure finally paid off in the 89th minute.
Philipp Lahm got to the byline down the right and fired a ball in which Gomez, sliding in, bundled over the line at the near post.
Real Madrid manager Jose Mourinho was not too downcast in defeat, however.
"It was a match that did not leave me with negative feelings," he said.
"It was a match that I don't think we deserved to lose but we lost, and football is like that."
Mourinho said he was "optimistic" that Real would turn the tie around at home.
"We'll have a tough game but, as I said, we don't have to get a crazy result, we have to play a good match and win 1-0, 2-0 or 3-1.
"I think the team has the capacity to do it."