Ali Mohamed Gedi fired Mohamed Afrah Qanyare, the national security minister, Musa Sudi Yalahow, the commerce minister militia, Issa Botan Alin, the rehabilitation minister, and Omar Muhamoud Finnish, the religious affairs minister, on Monday, a government spokesman said.
The spokesman, Abdirahman Nur Mohamed Dinari, said: "The prime minister, chairing the council of ministers, has sacked all the cabinet members who have been involved in the fighting."
The four commanders, members of the US-backed Alliance for the Restoration of Peace and Counter-Terrorism (ARPCT), had defied several orders to stop fighting with Mogadishu's increasingly powerful 11 Union of Islamic Courts since February.
In the latest clashes on Sunday, the gunmen seized control of the strategic town of Balad, about 30km north of Mogadishu, as the alliance fighters fled to the regional town of Jowhar, about 60km to the north.
The seizure of Balad, a supply town for the commanders, put the Islamic courts within striking distance of Jowhar.
Jowhar is controlled by Mohamed Omar Habeb, a commander and leading alliance member, and home to several aid agencies.
In addition, Gedi invited the Islamic courts union to take part in dialogue to end the clashes that started in February and have so far killed at least 347 people and injured more than 1,500, many of them civilians.
Dinari said: "The prime minister has invited the Islamic courts for dialogue."
The largely powerless Somali transitional government is based in the regional town of Baidoa, about 250km northwest of the capital.
The ARPCT, formed in February, has reportedly received financial and intelligence support from the US to help fight the Islamic courts, accused of harbouring foreign fighters and having links with groups such as al-Qaeda.
The courts deny the accusations and say the commanders are fighting for the "enemy of Islam".
The US has refused to confirm or deny its support for the ARPCT.