Security forces from Somalia's Puntland region have stormed a Panama-flagged cargo vessel held by pirates, freeing the ship's crew.
However, the pirates killed the Pakistani captain of the MV QSM Dubai during the confrontation on Wednesday, according to a Somalian government official.
"Our troops stormed the Panama-flagged vessel and engaged the pirates," Said Mohamed Raage, the ports and marine transport minister, said on Thursday.
"There was brief fighting before they defeated them.
"We arrested seven pirates after they killed the captain of the ship."
Two Somali soldiers were injured in the gun battle, which freed 24 crew members from Egypt, Pakistan, Bangladesh and Ghana.
Somali forces decided to use force after the pirates refused to surrender, Raage said.
The ship was carrying sugar from Brazil to Bossaso, a city in northern Somalia, he said.
The 15,220 tonne MV QSM Dubai was captured by pirates while it was travelling inside of the internationally recommended transit corridor.
Puntland, a semi-autonomous region in northern Somalia, is a base for pirate gangs targeting ships in the Gulf of Aden.
But the area is generally more peaceful than the rest of the country.