During the current fighting in Israel against Hamas the issue of Americans serving in the Israeli military came up. Israel revealed that about a thousand Americans were currently serving in the Israeli military. This was never a secret and Americans have been serving in the Israeli military since Israel became a country in 1948. In the 1948 war there were many experienced World War II American veterans fighting for Israel and many were killed. Americans, usually American Jews, subsequently served in every subsequent war Israel has been involved in.
Americans serving in any foreign military has always been technically illegal. But the laws, often quite murky and sometimes challenged, were rarely enforced successfully unless the American serving in foreign forces did so to deliberately cause harm to the United States. Thus Americans forced to serve in the British Royal Navy, which was the main cause of the War of 1812 between Britain and the U.S., often resulted in Americans being on British ships attacking American ships or even fighting American warships. Unless the American was an officer on the British ship, he was not liable to prosecution. Same in the 1847 Mexican-American War. But during that conflict some recent Irish migrants to the U.S. serving in the American army in Mexico had deserted and the joined the Mexican Army (fellow Catholics and all that). These men were considered traitors by the U.S. But ever since the American Revolution ended in 1780 American soldiers and sailors, often prominent officers, served in the armed forces of other nations..
Meanwhile the U.S. has always had lots of foreigners (non-U.S. citizens) in its armed forces. Since September 11, 2001 there have been efforts to recruit even more foreigners. For example in 2009 the U.S. Army made a major effort to recruit foreigners in the U.S. who had special skills (fluent in Arabic or Afghan languages, doctors, nurses) that were in great demand. There was some concern that this would provide a way for terrorist organizations, or foreign intelligence agencies to infiltrate the U.S. military but there was never any evidence of this happening. Recruiters believed they had adequate screening capabilities to prevent this.
The U.S. military currently had about 50,000 non-citizens in service (out of some 2.2 million active duty and reserve troops) at the height of the war on terror (2009). The navy, not the army, had the largest number (nearly half). That's something of a navy tradition, as hiring foreigners to serve on U.S. warships is a custom that goes back over a century. Currently, the proportion of foreigners (about two percent) in the U.S. military is historically low. It's been much higher in the past, often reaching 25 percent or more. This caused alarm, then as now, but there were never a lot of problems with uncertain loyalties.