After nearly nine years in Iraq, the war has formally drawn to a close as U.S. Defense Secretary Leon Panetta declared an end to its mission in a ceremony in Baghdad on Thursday.

Panetta, joined by the U.S. ambassador to Iraq, James Jeffrey, said the sacrifice had been worth the effort as it had set Iraq on a path to democracy.

Let me be clear: Iraq will be tested in the days ahead - by terrorism, and by those who would seek to divide, by economic and social issues, by the demands of democracy itself, Panetta said. Challenges remain, but the U.S. will be there to stand by the Iraqi people as they navigate those challenges to build a stronger and more prosperous nation.

As of last Friday, the war in Iraq had claimed 4,487 American lives, with another 32,226 Americans wounded in action, according to Pentagon statistics. Nearly 100,000 Iraqis have died in a war that cost the U.S. more than $800 billion.

Panetta and several other diplomatic, military and defense leaders participated in a symbolic ceremony during which the flag of U.S. Forces-Iraq was officially retired, or cased, according to Army tradition, The Associated Press reported. The U.S. Forces-Iraq flag was furled - or wrapped - around a flagpole and covered in camouflage. It will be brought back to the United States.

You will leave with great pride - lasting pride, Panetta told the troops. Secure in knowing that your sacrifice has helped the Iraqi people to cast tyranny aside and to offer hope for prosperity and peace to this country's future generations.

Despite the ceremony marking the end of the war, the military still has two bases in Iraq and roughly 4,000 troops, including several hundred who attended the ceremony; military officials reported that the remaining troops are still being attacked on a daily basis.

The Americans are leaving behind them a destroyed country, said Mariam Khazim of Sadr City, the AP reported. The Americans did not leave modern schools or big factories behind them. Instead, they left thousands of widows and orphans.

Around 200 U.S. military personnel will remain in Iraq after this year, functioning solely as members of the U.S. diplomatic mission by administering arms sales and deal with other limited military exchanges.

In the 45-minute ceremony, Panetta paid tribute to the troops who fought, saying:

You came to this land between the rivers, again, again and again. You did not know that you would return to your loved ones. You will leave with great pride, secure in knowing that your sacrifice has helped the Iraqi people begin a new sacrifice free from tyranny.