BAGHDAD — Islamic militants overran much of Iraq’s second-largest city of Mosul on Tuesday, seizing the governor’s headquarters and rampaging through police stations, military bases and the airport as security forces collapsed and abandoned their posts. Gunmen cruised through neighborhoods, waving black banners while residents fled.

The assault was a heavy defeat for Prime Minister Nouri al-Maliki in the face of a widening insurgency by a breakaway al-Qaida group, the Islamic State of Iraq and the Levant. The group has been advancing in both Iraq and neighboring Syria, capturing territory in what appears to be a campaign to set up a militant enclave straddling the border.

Earlier this year, Islamic State took control in another Iraqi city, Fallujah, in the west of the country, and government forces have been unable to take it back. The far larger Mosul is an even more strategic prize. The city and surrounding Ninevah province are a key export route for Iraqi oil and a gateway to Syria.

In a sign of the weight of the blow, al-Maliki pressed parliament to declare a state of emergency that would grant him greater powers.

Regaining Mosul poses a daunting challenge for the Shiite prime minister. The city has a Sunni Muslim majority and many in the community are already embittered against his Shiite-led government.

During the nearly nine-year American presence in the country, Mosul was a major stronghold for al-Qaida and U.S. and Iraqi forces carried out repeated offensives there, regaining a semblance of control but never routing the insurgents entirely.