Dortmund, who beat Darmstadt 2-0, are now five points off Bayern and host the champions this weekend.
Bayern, who had won 17 consecutive home games in all competitions, trailed when Mainz's Jairo swept home a cross.
Arjen Robben levelled from 25 yards but substitute Jhon Cordoba scored a late winner from outside the box.
Dortmund, who have now won six of their last seven Bundesliga matches, beat Darmstadt thanks to goals from Adrian Ramos and Erik Durm.
There will be live text commentary of Der Klassiker on the BBC Sport website (Saturday, 17:30 GMT kick-off).
Bayern Munich suffered a surprise defeat by Mainz as Borussia Dortmund boosted their Bundesliga title hopes going into Saturday's Der Klassiker.