Two suicide bombers arrived by motorbike near the entrance of the barracks in Cherchell soon after iftar -- when Muslims break their daily fast during the holy month of Ramadan, a security source said.
"Of the 18 dead, there are 16 servicemen and two civilians," a hospital source said.
The town of Cherchell, home to ancient Roman ruins, lies just under 100 km (60 miles) west of the capital Algiers.
Algeria, an energy exporter in North Africa, is still emerging from nearly two decades of conflict between security forces and Islamist militant groups.
In the past few years the violence has been reduced significantly, but the militants -- who now operate as Al Qaeda in the Islamic Maghreb (AQIM) -- still carry out ambushes, kidnappings and occasional bombings.
One the last major attacks was in August 2008, when a bomb attack targeting a paramilitary gendarmerie training school at Issers, east of Algiers, killed 48. In June 2009, insurgents killed 18 paramilitary police officers and one civilian, according to officials, in an ambush.
Algeria has said it believes the chaos inside neighbouring Libya, and large quantities of weapons circulating there, are being exploited by AQIM, which has weapons, a safe heaven in the Sahara desert and huge sums of money earned from kidnapping.
The location of Cherchell is unusual, as attacks have usually occurred east of the capital such as in the mountainous Kabylie region, where AQIM has a stronghold.
Algeria has taken a leading role in combating AQIM, in part because the organisation is led by Algerian nationals and grew out of the Salafist Group for Preaching and Combat, which fought a long insurgency against Algeria's security forces.
"Al Qaeda's main target is the capital Algiers but it failed to hit it, that is why it is operating around the capital," Sameur Riad, a security analyst at Algeria's El Khabar newspaper, said.
Al Qaeda's North African wing this month claimed responsibility for a suicide bombing on a police headquarters in the town of Tizi Ouzou that officials said injured 29 people.