The gunman killed one police officer and one biology teacher, police said. Another policeman was shot and injured.
The hostages the gunman took have been released, police said.
The incident, on the outskirts of Moscow, comes as Russia prepares to host the Winter Olympic Games, due to start in Sochi this week.
The gunman is believed to be a pupil at School No. 263 on the northern outskirts of Moscow.
“The person who took 20 people and a teacher hostage is a student in the upper classes at the same school,” an interior ministry spokesman said on state TV.
“He has been neutralized and all the students have been freed,” he said.
“One policeman was fatally wounded during the operation and died in hospital, and a teacher at School No. 263 was also killed,” he added.
It is not clear how the teacher and the policeman died.
A school official told Russian television that all children and teachers had been evacuated from the school after the incident.
The gunman opened fire on police officers who arrived at the scene, reports say.
QVk2v-eGPtYImage source: Wikimedia Commons President-elect Donald Trump celebrated his election victory at the Ultimate Fighting…
Millions of voters across the US chose to return Donald Trump to the White House…
Donald Trump declares victory in the US election as he addresses jubilant supporters in Florida.…
Stocks around the world are rising as Donald Trump appears to be on the cusp…
Donald Trump has won Pennsylvania, North Carolina and Georgia and taken a lead over Kamala…
Quincy Jones, the celebrated musician and producer who worked with Michael Jackson, Frank Sinatra, Ray…