It took place in a northeastern district of the Spanish capital at around midday (1100 GMT) and the man was taken to hospital in a serious condition, the emergency services said.
“We treated a man who had suffered serious burns and took him to La Paz hospital,” an emergency services spokesman told AFP.
Police sources confirmed the man “had set himself on fire outside the Moroccan consulate” but were unable to give further details.
Details of the incident were confirmed by a Moroccan diplomatic source.
“The person set himself on fire next to the consulate. We have no idea why he did it. It happened very quickly,” the source told AFP.
“There was no contact with the consulate, it happened just outside.”
Unconfirmed media reports said the man was a Moroccan national in his 40s, with an eyewitness telling Spain’s RTVE public television he saw what happened while driving past.
“I saw him running and there were people behind him trying to pull his clothes off,” said the witness, who gave his name as Rasheed, adding that he saw someone running over with a fire extinguisher to try and put out the flames.
“From the way the flames were starting from his head, I think he had poured petrol over himself.”