Al-Shabab has attacked two Somali military bases using an explosive-laden vehicle driven by a suicide bomber along with dozens of heavily-armed fighters.

At least 12 Somali soldiers were killed in the attack on Wednesday, and the attackers briefly captured a base southwest of the capital, officials said, underscoring the group's ability to launch attacks despite a government offensive.

More:

A suicide bomber detonated at the el-Salini base before gunmen stormed in and briefly occupied it, police said. The military recaptured the base after reinforcements arrived.

"They took the base and took weapons and ammunitions, this includes anti-aircraft guns fixed on pickups," said Nur Ahmed, a police officer from Afgoye in Lower Shabelle region.

Military Officer Ismail Ali said 12 soldiers were killed and the commander of the base was injured.

African Union troops stepped in to help repel the second, larger attack after a bomber drove a vehicle onto a bridge leading to the Qoryooley army base, 95 kilometres (59 miles) west of the capital Mogadishu and detonated it.

"The terrorists carried out an ... attack on the military bases at Qoryooley and El-Salini but our brave boys repelled them. They [al-Shabab] have suffered heavy casualties this morning and the army is in full control in both areas now," said Mohamed Adan, a Somali military commander in a nearby town.

"They have destroyed part of the bridge across the entrance to Qoryooley where the Somali military base is located using a vehicle loaded with explosives," he added.

He said the AU peacekeeping force, African Union Mission to Somalia (AMISOM), helped fight the al-Qaeda-linked fighters. Witnesses said dozens of heavily-armed al-Shabab fighters entered Qoryooley town and addressed a gathering of residents before retreating.

"The al-Shabab fighters entered the town and one of their commanders spoke with a gathering before they made their way out of the town. The situation is quiet now and the Somali forces backed by AMISOM soldiers are patrolling the streets," Ali Moalim, a resident in Qoryooley, told the AFP news agency by phone.

Al-Shabab claimed responsibility for the attack in a statement saying they "captured a sizeable amount of military supplies".

The group has fought for more than a decade to topple the internationally-recognised Somali government and carries out regular attacks against civilian and government targets, despite losing much of the territory it once controlled.