The May 19 election is seen by many as a referendum on the global agreement over Iran's nuclear program that Rouhani helped negotiate.
Ahmadinejad's decision runs directly counter to advice offered in September by Iran's Supreme Leader Ayatollah Ali Khamenei, who has final say over all state matters.
"The supreme leader requested that I don't stand and I had accepted", Mr Ahmadinejad told reporters. There was no immediate reaction from Khamenei's office.
Ahmadinejad was accompanied by his confidant former controversial deputies Hamid Baqaee and Rahim Mashae.
Ahmadinejad served two four-year terms between 2005 and 2013 and is now eligible for reelection after four years outside office under Iranian law.
Iran's economy suffered under heavy worldwide sanctions during his administration because of western suspicions that Tehran was secretly pursuing nuclear weapons. Then, on April 12 ex-President Ahmadinejad threw a curve ball into the race with his announcement that he intends to run.
Over the past year, Raisi has been touted as a frontrunner to become Khamenei's successor, a higher position than that of the president.
All potential candidates have to be vetted by the Guardian Council and many observers believe Mr Ahmadinejad will not pass this hurdle.
Registration will last for five days, followed by a period of time when the registrants will be screened for their political and Islamic qualifications by the hardline and religious body tasked with vetting, the Guardian Council.
There has been heated debate over whether the council has the constitutional footing to block candidates.
In this Monday, June 15, 2009, photo, hundreds of thousands of supporters of leading opposition presidential candidate Mir Hossein Mousavi, who claims there was voting fraud in Friday's election, turn out to protest the result of the election at a mass rally in Azadi (Freedom) square in Tehran, Iran.
Just when it appeared Ahmadinejad would be leaving, he turned around and returned to the Interior Ministry's registration desk, pulling out his identification documents with a flourish in front of a melee of shouting journalists. He recently joined Twitter.
On the first day of registration of candidates on Tuesday, 126 persons, including six women, had submitted their name.
Registration will remain open until Saturday, and any Iranian national can apply. Iran agreed to limit its enrichment of uranium in exchange for the lifting of some economic sanctions.