Police have surrounded the building in Malmesbury near Cape Town outside which a body lay under a tree and a penknife had been discarded nearby, said an AFP correspondent at the scene. The attacker's motive remains unclear.
Police were alerted by early morning worshippers and arrived at Malmesbury's mosque to find two people had died of stab wounds, Western Cape police spokeswoman Noloyiso Rwexana, told AFP.
"The suspect, believed to be in his thirties and armed with a knife, charged at the police who tried to persuade him to hand himself over," she said.
"He ignored the calls and tried to attack police. He was shot dead."
Rwexana said police are now "combing the scene for clues".
Local media said the suspect was Somali, but police have not confirmed this.