President Andres Manuel Lopez Obrador, who moved into the centuries-old palace as he took office last year and turned the former presidential residence into a museum at part of his government's austere measures, was not in at the time of the shooting on Saturday, Efe news reported.
The Mexico City police said they received a radio alert about the shooting in a small residential building on a narrow street which leads to one of the entrances of the palace.
When police arrived at the spot, they found four people with gunshot wounds lying in the building courtyard and a man carrying a weapon standing nearby.
The gunman was asked to drop the weapon but he ignored the call and opened fire, forcing an officer to retaliate and shoot the attacker dead.
Preliminary reports indicate that the gunman entered the building to relieve himself.
He was reproached by the neighbours for urinating in the courtyard after which he took his gun out and fired shots hitting five people.
Paramedics confirmed three people, including the gunman, were dead at the spot.
Three more people were wounded. One of them succumbed to his injuries as the wounded were being taken to hospital.
The street in the historic center of the capital ends at the side of the National Palace where President Lopez Obrador usually holds meetings with journalists.