By Kay Johnson

KABUL (Reuters) - The U.S.-led coalition in Afghanistan formally ended its combat mission on Sunday, more than 13 years after an international alliance ousted the Taliban government for sheltering the planners of the Sept. 11, 2001 attacks on American cities.

About 13,000 foreign troops, mostly Americans, will remain in the country under a new, two-year mission named "Resolute Support" that will continue the coalition's training of Afghan security forces.

The Afghan army and police are struggling to fight against Taliban militants who this year killed record numbers of Afghans.

"Today marks an end of an era and the beginning of a new one," said U.S. General John Campbell, commander of the International Security Assistance Force (ISAF), at the ceremony marking the end of the mission held at the ISAF headquarters in Kabul.

"We will continue to invest in Afghanistan's future," Campbell said at the ceremony, during which he rolled up the coalition's flag.

Since 2001, nearly 3,500 foreign soldiers have died in the Afghan war, including around 2,200 Americans.

"Now, thanks to the extraordinary sacrifices of our men and women in uniform, our combat mission in Afghanistan is ending, and the longest war in American history is coming to a responsible conclusion," President Barack Obama said in a statement.

The late al Qaeda leader Osama bin Laden had strong relations with the Taliban, who let him and other members of his global militant network hide in Afghanistan.

The Taliban have launched increasingly deadly attacks in the past year. Nearly 3,200 Afghan civilians were killed in the conflict between the militant group and the army in 2014, and more than 4,600 Afghan army and police died in Taliban attacks.

For Afghanistan's new president, Ashraf Ghani, keeping government control of territory and preventing security from further deteriorating is a top priority.

ISAF said it had withheld details of Sunday's ceremony until the last moment for fear the insurgents might attempt an attack with rockets or mortars.

(Additional reporting by Jessica Donati and Eric Beech in Washington; Editing by Eric Walsh)