CAIRO — At least 21 Egyptian soldiers were killed on Saturday when heavily armed gunmen attacked a border guard post near a remote desert oasis, according to an army spokesman.

The death toll appeared to be the highest for the military in a single attack in recent memory, and came as the Egyptian government has expressed growing alarm at threats from neighboring countries, and especially from Libya, an increasingly lawless state that shares a long border with Egypt.

The episode occurred around 6 p.m. near the isolated Farafara oasis in Egypt’s western desert, about 120 miles from the Libyan border. During the attack, one of the gunmen fired a rocket-propelled grenade that struck an ammunition cache, causing an explosion that killed the soldiers and wounded four others, according to a military statement.

The military did not provide any information about the gunmen, except to call them “terrorists.” Egypt’s security services have been repeatedly attacked over the past year, mostly in the Sinai Peninsula, from militant groups mounting what they said were retaliatory strikes after the security services killed hundreds of supporters of the ousted President Mohamed Morsi at demonstrations last summer.