BAGHDAD — Sunni militants spilling over the border from Syria on Tuesday seized control of the northern city of Mosul, Iraq’s second largest, in the most stunning success yet in a rapidly widening insurgency that threatens to drag the region into war.

Having consolidated control over Sunni-dominated Nineveh Province, armed gunmen were heading on the main road to Baghdad, Iraqi officials said, and had already taken over parts of Salahuddin Province. Thousands of civilians fled south toward Baghdad and east toward the autonomous region of Kurdistan, where security is maintained by a fiercely loyal army, the pesh merga.

The Iraqi Army apparently crumbled in the face of the militant assault, as soldiers dropped their weapons, shed their uniforms for civilian clothes and blended in with the fleeing masses. The militants freed thousands of prisoners and took over military bases, police stations, banks and provincial headquarters, before raising the black flag of the jihadi group Islamic State of Iraq and Syria over public buildings. The bodies of soldiers, police officers and civilians lay scattered in the streets.