Ghalibaf called on his supporters to back conservative cleric and jurist Ebrahim Raisi in Friday's vote.
Ghalibaf called on his supporters to back conservative cleric and jurist Ebrahim Raisi in Friday's vote, saying it was vital for the "preservation of the interests of the people, the revolution and the country".
Unofficial polls still show Rouhani, a moderate cleric who has sought to improve civil liberties and rebuild ties with the West, as the front-runner.
But he has faced a harder-than-expected challenge from the conservatives due to the continued stagnation of the economy.
Raisi, a former prosecutor-general and close ally of supreme leader Ayatollah Ali Khamenei, has called for a more assertive approach to the West and a focus on building a self-sufficient "resistance economy".
This had been Ghalibaf's third bid for the presidency, having been runner-up to Rouhani in 2013.
A former police chief and member of the Revolutionary Guards, he has played on his tough-guy image in the past, but this year targeted his campaign against the wealthy elite, whom he dubbed the "four-percenters".
"A fundamental and crucial decision must be taken for the unity of the revolutionary front," Ghalibaf wrote in a statement announcing his withdrawal.
"To protect this great ideal, I ask all of my supporters across the country to offer all of their support to the success of our dear brother Ebrahim Raisi."
He launched brutal tirades against Rouhani and his reformist allies in the televised debates, accusing them of corruption and failing to support the poor.
"The expectation of us and the people is that this decision sets the stage for a new era of economic transformation that, by cutting off the four-percenters from the economy, will lead to youth employment and support for the underprivileged and poor in Iran.
"The fight has just begun," he said.
Rouhani's government signed a 2015 nuclear deal with world powers that ended some sanctions in exchange for curbs to Iran's nuclear programme.
But it has struggled to attract the large-scale foreign investments Rouhani had promised when the deal came into force, and which he said were necessary to reduce unemployment and kick-start the economy.
Raisi is currently the head of the powerful Imam Reza shrine and charitable foundation in the holy city of Mashhad who has attracted support from traditional conservatives, and is seen as the favoured candidate of the security establishment.
Three other candidates -- reformists Eshaq Jahangiri and Mostafa Hashemataba, and conservative Mostafa Mirsalim -- are also standing in the election, though they are considered relatively marginal figures who may also withdraw before the vote.
Iran's elections are similar to the French system in which a second round run-off is held between the top two candidates unless one wins 50 percent or more in the first round.
Rouhani squeaked through in the first round of 2013 with 50.7 percent of the vote.