The gun man, a newly-trained Somali soldier, was also shot dead in the Gordon military base managed by the UAE, the officer, who gave his name only as Ahmed, said.

"The soldier opened fire on the UAE trainers and Somali military officials when they started praying. Four UAE officers were injured while four Somali soldiers died," the officer told Reuters.

"We understand the soldier had defected from al Shabaab before he was recruited as a soldier by Somalia and UAE," he said.

Al Shabaab, linked to al Qaeda, claimed responsibility for the attack via a statement on its Radio al Andalus and said its fighters had killed 17 soldiers.

Two nurses and a doctor at the Erdogan Hospital in Mogadishu, who asked not to be named, told Reuters a senior officer from the UAE had died and four other officers were seriously injured.

In addition about ten injured Somali soldiers had been brought to the hospital, they said.

Somalia's President Hassan Sheikh Mohamud in a statement on state media (SONNA) offered his condolences to the UAE following the incident.

Al Shabaab has waged an insurgency against the Somali government since 2006 to try to establish its own rule.

(Reporting by Abdi Sheikh; Writing by Elias Biryabarema in Nairobi and Surbhi Misra in Bengaluru;Editing by Barbara Lewis)