Port and Marine Transport minister Mohamed Raage said Thursday the soldiers stormed the QSM Dubai cargo ship, which had been seized a day earlier.
Raage said the two sides traded shots until the soldiers were able to subdue and arrest the hijackers. But he said the hijackers had already killed the captain of the ship.
The Panama-flagged cargo vessel and its 24 crew members were on their way through the Gulf of Aden from Brazil.
The incident comes just after the crew of a Libyan-owned cargo ship managed to regain control of their hijacked vessel after four months in captivity.
The European Union's anti-piracy force says the crew fought Wednesday to take back the merchant vessel RIM. One crew member was injured and several pirates are believed to have died in the violence.
The EU force says it sent the closest warship to provide medical assistance. It says pirates on another vessel tried to block the warship, but were not successful.
The EU and other world powers are patrolling the waters off Somalia in an effort to protect shipping lanes. Despite this, Somali pirates have hijacked dozens of vessels in the past few years and taken in tens of millions of dollars in ransom.
The pirates currently hold more than 20 ships with about 400 crew members.