"Al-Qaeda's top ranks have been hammered. The core of al-Qaeda in Afghanistan and Pakistan is on the way to defeat," Obama told nearly 3,000 Marines in attendance at Camp Pendelton in California.
More than 320 Marines based at Camp Pendleton have been killed in combat operations in Afghanistan.
"This is still a hard fight," Obama said. "It's still tough, and we're still needed."
Obama said more Afghans are reclaiming their communities - their markets, their schools, their towns - and they have a chance to forge their own future.
More From This Section
But the end of the war in Afghanistan doesn't mean the end of threats to the US, he said.
"As I've said before, even as we decimated the al-Qaeda leadership that attacked us on 9/11, al-Qaeda affiliates and like-minded extremists still threaten our homeland, still threaten our diplomatic facilities, still threaten our businesses abroad. And we've got to take these threats seriously and do all we can to confront them. We've been reminded of this again in recent days," he said.
Obama said the United States is never going to retreat from the world. "We don't get terrorised. We're going to keep standing up for our interests. We're going to keep standing up for the security of our citizens," he said.
"We're going to keep working with our allies and our partners. We're going to keep offering a future of hope and progress - in stark contrast to terrorists who only know how to kill and destroy and maim. And like generations before us, the United States of America is going to remain the greatest force for freedom that the world has ever known," Obama said.
"We have to have a military strategy to protect ourselves. But we've also got to lead with our values and our ideals and all elements of our power," he added.