MOSUL, Iraq — Dressed in a military uniform, Prime Minister Haider al-Abadi arrived here in Mosul on Sunday to congratulate Iraq’s armed forces for wresting the city from the Islamic State. The victory marked the formal end of a bloody campaign that lasted nearly nine months, left much of Iraq’s second-largest city in ruins, killed thousands of people and displaced nearly a million more.

While Iraqi troops were still mopping up the last pockets of resistance and could be facing guerrilla attacks for weeks, the military began to savor its triumph in the shattered alleyways of the old city, where the Islamic State, also known as ISIS or ISIL, put up a fierce last stand.

Hanging over the declaration of victory is the reality of the hard road ahead. The security forces in Mosul still face dangers, including Islamic State sleeper cells and suicide bombers. And they must clear houses rigged with explosive booby traps so civilians can return and services can be restored.

Mosul was the largest city in either Iraq or Syria held by the Islamic State, and its loss signifies the waning territorial claims of a terrorist group that had its beginnings in the aftermath of the American invasion of Iraq in 2003. The group is also threatened with the loss of its de facto capital, the Syrian city of Raqqa, which is encircled by Arab and Kurdish fighters supported by the United States.