The car bomb in Howlwadag district killed three soldiers and injured 14 people, including six children, local officials told BBC Somali.
The blast also damaged nearby houses and blew the roof off a mosque.
The militant group al-Shabab, which has waged an insurgency for more than 10 years, said it carried out the attack.
The three soldiers had died as they stopped the explosives-laden car from entering a government compound, local official Salah Hassan Omar said.
Raqiya Mahamed Ali, who was in the compound at the time, said: "We were in the middle of our usual work when the explosion happened.
"I hid under the table. There was a lot of gunfire at our gate... when I came out, I saw many people injured on the ground and others dead," she told Reuters.
Somalia has faced instability and violence since 1991, when the military government was overthrown.
The ousting of Mohamed Siad Barre led to a decades-long civil war between rival warlords, and two northern regions - Somaliland and Puntland - effectively broke away from Somalia.
Much of the country has effectively been a war zone.
A UN-backed unity government was formed in 2012. Al-Shabab has since been driven out of many urban areas but still controls territory in rural regions and carries out gun attacks and bombings on military and civilian targets.
The militant group has imposed a strict version of Sharia in areas under its control, including stoning to death women accused of adultery and amputating the hands of thieves.
A truck attack in Mogadishu in October last year killed at least 500 people in the deadliest bombing in Somalia.
A man accused of leading an al-Shabab unit that carried out the attack was sentenced to death in February.