Haider Ali Hussein, a porter at a nearby utilities shop, said that for security reasons, the mosque was reserved for people from the neighborhood, Sinak. The guard had tried to block the bomber’s entry because he did not recognize him.

“Very good friends of mine, gone in this explosion,” Mr. Hussein said.

The attack was the second against a Shiite mosque in Baghdad this week. On Sunday, a suicide bomber detonated his explosives vest outside a Shiite mosque in the Harthiya neighborhood of western Baghdad, killing 18 people and wounding 35, the authorities said. Two roadside bombs in the capital on Sunday killed another 8 and wounded 12, officials said.

As the Islamic State has tried to press closer to Baghdad, Iraqi and American officials have insisted that the capital is well protected from a siege and that the most the militants could hope to do was sow fear and death with bombings.

But on Monday, residents of the capital were reminded that mortal threats abound in the city beyond those posed by the Islamic State, especially amid the growth of government-supported militias and the proliferation of weapons.

Shortly after midnight, a protracted firefight between a federal police unit and another armed group erupted along a darkened and otherwise empty boulevard of the Karrada neighborhood, Interior Ministry officials said. The shootout, involving assault rifles and heavy machine guns, lasted at least 20 minutes though remarkably, officials said, only two police officers were wounded.

Saad Maan, the spokesman for the Interior Ministry, said in an interview that the police had converged on a hotel where “a gang” was holding a kidnap victim. The woman, the relative of a prominent Kurdish politician, had been kidnapped in Basra about two weeks ago and her captors were demanding a $2.5 million ransom, officials said.

The woman escaped her captors during the shootout, Mr. Maan said, yet there were no arrests in the case and it still remained unclear late Monday which group was responsible.