The country, however, appeared to have escaped major damage and casualties.
The US Geological Survey said the earthquake's epicenter was 36 kilometers (22 miles) northwest of Tecpan, near the Pacific resort of Acapulco in southwestern Guerrero state.
The quake struck at a depth of 24 kilometers.
Mexico's National Seismology Service gave the same magnitude for the quake, saying it was followed by dozens of weaker aftershocks of up to magnitude 4.8.
Tourists in Acapulco for Holy Week streamed out of hotels. Buildings were also evacuated in Mexico City as helicopters buzzed overhead to check for damage.
The earthquake was also felt in the eastern state of Veracruz and the southern states of Oaxaca and Chiapas.
Angelica Lasso, a 30-year-old website designer, grabbed a jacket and ran out of the first floor of her three-story apartment building in Mexico City.
"The furniture moved and my CDs fell from the disc storage tower. I got out quickly and even forgot my house keys," Lasso said as she bought a sugary bread from a street vendor.
Authorities were working to restore electricity in several city neighborhoods.
"Fortunately, what we have are collapsed walls and no reports of deaths or injuries," said federal civil protection director general Ricardo de la Cruz.
Mexico City Mayor Miguel Angel Mancera said some walls collapsed and a few roads were damaged but nobody was injured.
The metropolis of 20 million people is sensitive to distant earthquakes because it was built over soft soil from a drained lake.