During the operation five prisoners and three soldiers were killed while 21 people, the majority of them inmates, were injured, Abdiqani Mohamed Qalaf, spokesperson for the prison service, said on Facebook.
He blamed "a violent group" among the prisoners for the attack.
No prisoners had escaped and an investigation into how the attack occurred will be conducted, he added.
"Somalia's prison forces concluded an operation in which prisoners fought inside the cell. Prisoners who tried to fight were shot dead," Somalia National TV said.
It said the inmates who died were members of the terrorist group Al Shabab who had been sentenced to death.
Two security personnel at the prison told Reuters grenades and guns had been smuggled into the cell and the inmates had used them to start the firefight.
AMK/PR