White House press secretary Sarah Sanders announced the unscheduled visit in a Twitter post.
"President Trump and the first lady traveled to Iraq late on Christmas night to visit with our troops and senior military leadership to thank them for their service, their success, and their sacrifice and to wish them a Merry Christmas," Sanders wrote.
Trump gave remarks to about 100 troops at Al Asad Air Base west of Baghdad before taking questions from reporters.
Though it was Trump's first visit to a combat zone, it wasn't his first time visiting troops overseas. He spoke with service members at Sigonella Naval Air Station in Sicily, Italy, in May 2017, four months after taking office. He also met with troops during a trip to South Korea in November 2017.
The visit came days after the Trump administration ordered the withdrawal of all U.S. forces from neighboring Syria. Troops in both countries have been engaged in a battle against Islamic State militants.
While speaking to reporters, Trump defended the withdrawal, saying he gave generals multiple six-month extensions to vacate the country.
"The United States cannot continue to be the policeman of the world," he said. "We don't want to be taken advantage of any more by countries that use us and use our incredible military to protect them. They don't pay for it, and they're going to have to."
Speaking on border security and the government shutdown, Trump said the shutdown will last as long as it takes to get funding for the wall.
"We need a wall. We need safety for our country. Even from this standpoint. We have terrorists coming in through the southern border," he said, adding that he plans to visit the border before his State of the Union address.
During a refueling trip in Ramstein Air Base in Germany, the president and first lady greeted troops for about 45 minutes in the hangar. His unscheduled remarks were not available to the pool reporter.
Air Force One then headed back to Joint Base Andrews in Maryland, where the trip began at 12:06 a.m. Wednesday.