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.
But the end of the Islamic State’s hold on Mosul does not mean peace is at hand. Other cities and towns in Iraq remain under the militants’ control, and Iraqis expect an increase in terrorist attacks in urban centers, especially in the capital, Baghdad, as the group reverts to its insurgent roots.
“It’s going to continue to be hard every day,” said Col. Pat Work, the commanding officer of the Second Brigade, 82nd Airborne Division, which is carrying out the American advisory effort here.
“Iraqi security forces need to be on the top of their game, and we need to be over their shoulder helping them as they move through this transition to consolidate gains and really sink their hold in on the west side,” Colonel Work said as he rolled through the streets of western Mosul recently in an armored vehicle. “ISIS will challenge this.”
The victory could have been sweeter as the Iraqis were denied the symbolism of hanging the national flag from the Grand al-Nuri Mosque and its distinctive leaning minaret, which was wiped from the skyline in recent weeks as a final act of barbarity by Islamic State militants who packed it with explosives and brought it down as government troops approached.
It was at that mosque in June 2014 where Abu Bakr al-Baghdadi strode to the top of a pulpit and declared himself the leader of a caliphate straddling the borders of Iraq and Syria, a vast territory where for three years Islamist extremists have governed with a strict form of Islamic law, held women as sex slaves, carried out public beheadings and plotted terrorist attacks against the West.
This past week, as fighting raged nearby, Iraqi soldiers took selfies in front of the stump of the minaret and posed at the spot where Mr. Baghdadi made his speech. Destruction surrounded them, as did the stench of decaying bodies of Islamic State fighters, left to rot in the blazing sun.
The battle for Mosul began in October, after months of planning between Iraqis and American advisers, and some Obama administration officials had hoped it would conclude before they left office, giving a boost to the departing president’s efforts to defeat the Islamic State.
Instead, it lasted until now, and it was far more brutal than many expected. With dense house-to-house fighting and a ceaseless barrage of snipers and suicide bombers, the fight for Mosul was some of the toughest urban warfare since World War II, American commanders have said. Iraqi officers, whose lives have been defined by ceaseless war, said the fighting was among the worst they had seen.
“I have been with the Iraqi Army for 40 years,” said Maj. Gen. Sami al-Aradi, a commander of Iraq’s special forces. “I have participated in all of the battles of Iraq, but I’ve never seen anything like the battle for the old city.” He continued: “We have been fighting for each meter. And when I say we have been fighting for each meter, I mean it literally.”
Even as Mr. Abadi arrived here outfitted in the black uniform of Iraq’s elite Counterterrorism Service, Iraqi forces were pressing to erase a pocket of Islamic State resistance by the Tigris River. Speaking from his base in the old city, Lt. Gen. Abdul-Wahab al-Saadi, a senior commander in that service, said that the militants’ enclave was about 200 yards long and 50 yards wide and that he expected it to be taken later in the day or on Monday.
After arriving here, Mr. Abadi met with the Federal Police, who have taken significant losses in the battle, and went to visit the joint command overseeing the operation. But in an acknowledgment that the victory he had come to proclaim was not completely sealed, Iraqi officials said the prime minister would not make a public statement until the last patch of Islamic State territory in Mosul was cleared.
Earlier in the day, a post on Mr. Abadi’s official Twitter account stated that he had come to Mosul “to announce its liberation and congratulate the armed forces and Iraqi people on this victory.”
Some militants had sought to escape by swimming across the river, but General Saadi said his soldiers had shot them. The general said he had planted the Iraqi flag on the banks of the Tigris on Sunday morning — an act he described as a “special moment” in which he reflected on the many soldiers he had lost in the long battle.
The retaking of the city, by all accounts, came at a great cost. Sensitive to the mounting casualties, the Iraqi government does not disclose how many of its troops have been killed. But deaths among Iraqi security forces in the Mosul battle had reached 774 by the end of March, according to American officers, which suggests the toll is more than a thousand now.
Even more civilians are estimated to have been killed, many at the hands of the Islamic State and some inadvertently by American airstrikes. At least seven journalists were killed, including two French correspondents and their fixer, an Iraqi Kurdish journalist, in a mine explosion in recent weeks.
The Iraqis and their international partners will now be confronted by the immense challenge of restoring essential services like electricity and rebuilding destroyed hospitals, schools, homes and bridges, which were wrecked in the ground combat or by the airstrikes, artillery fire and Himars rocket attacks carried out by the American-led coalition to help Iraqi troops advance.
“When the fighting stops, the humanitarian crisis continues,” said Lise Grande, the deputy special representative for Iraq for the United Nations secretary general.
Western Mosul, especially its old city, where the Islamic State made its last stand, was hit particularly hard, becoming a gray and decimated landscape. As the combat has drawn to a close, thousands of civilians have begun to return. But 676,000 of those who left the western half of the city have yet to come back, according to United Nations data.
It is not hard to see why. Of the 54 neighborhoods in western Mosul, 15 neighborhoods that include 32,000 houses were heavily damaged, according to data provided by Ms. Grande. An additional 23 neighborhoods are considered to be moderately damaged. The cost of the near-term repairs and the more substantial reconstruction that is needed in Mosul has been estimated by United Nations experts at more than $ 700 million, she said.
In the heart of the old city, craters littered intersections and roadways, marking the places where bombs pummeled the ground, dropped from coalition warplanes. Street after street was covered in soaring piles of rubble, with rebar poking out of shattered masonry.
In a church used as a weapons-making factory by the Islamic State, mortars were lying on the ground next to a pink backpack decorated with a picture of a kitten. When troops unzipped the backpack, they found plastic sachets of a white explosive powder, which they identified as C4 used in militants’ bombs.
The military victory in Mosul has come without a political agreement between Iraq’s two largest communities, Sunni and Shiite Arabs, whose stark sectarian divisions led to the rise of the Islamic State. For many members of Iraq’s minority Sunnis, the Islamic State was seen as a protector against abuses they had suffered under Iraq’s Shiite-led government, especially under the former prime minister, Nuri Kamal al-Maliki.
After the Islamic State seized Mosul in 2014, many Sunnis welcomed them. Mr. Maliki was then removed from office, replaced by Mr. Abadi, a more moderate and less sectarian leader, but one widely viewed as weak. Under Mr. Abadi, there has been no meaningful reconciliation.
“I will leave Mosul because it has become a destroyed city,” said Aisha Abdullah, a teacher who endured life under the Islamic State. “In every corner of it there is memory and blood.”
And while the Islamic State, with its harsh rule, alienated many of the Sunni residents it sought to represent, residents said its ideology caught on among some of the population, particularly young men.
“There is no use in reconstructing the city if the people of Mosul don’t change,” Ms. Abdullah said. “There are still many people who assist ISIS, and the acts of violence will never end.”
Marwan Saeed, another Mosul resident, who lives in the city’s east side, which was liberated in January and where life has largely been restored to normal, with schools and shops reopening and most civilians returning home, said he feared for the future, now more than ever.
“Frankly, I’m desperate over the future,” he said. “ISIS destroyed the people’s mentality, and the wars destroyed the infrastructure, and we paid the price. There is no such thing as the phase ‘after ISIS.’ ISIS is a mentality, and this mentality will not end with guns alone.”
Iraqi forces still have to retake several Islamic State strongholds: Hawija and Tal Afar in northern Iraq and a series of towns in Iraq’s Euphrates River valley, stretching from Anah to Qaim.
While this is happening, Syrian fighters backed by American firepower are to complete the taking of Raqqa before moving to surround and kill the militants in Euphrates River towns on the Syrian side of the border.
“Mosul and Raqqa is not the end of it by any stretch of the imagination,” said Brig. Gen. Andrew A. Croft, a senior Air Force officer with the American-led task force that is fighting the Islamic State.
And there is the fear that many Islamic State fighters who were not captured or killed had simply put down their guns and blended in with the civilian population, to live to fight another day.
The wives of Islamic State fighters also pose a risk. In the last week, a woman holding a baby and wearing a long-sleeved robe that disguised a hand-held detonator tried to blow herself up as she approached an Iraqi soldier, said Second Lt. Muntather Laft, a media officer with the Counterterrorism Service.
“Do you know that most of the ISIS fighters have shaved their beards and took off their clothes, and now they are free?” said Zuhair Hazim al-Jibouri, a member of Mosul’s local council.