SESTO SAN GIOVANNI, Italy — It was a routine identity check, the kind Italy has relied on to stem the flow of illegal migration deeper into Europe. But the man stopped by two police officers around 3 a.m. Friday outside the northern city of Milan was anything but an ordinary drifter.

He turned out to be perhaps Europe’s most wanted man, Anis Amri, the chief suspect in the deadly terrorist attack on a Christmas market in Berlin that killed 12 people. Asked to show his papers and empty his backpack, he pulled out a gun, shot one officer, and in turn was shot and killed by another.

“Police bastards,” Mr. Amri, who turned 24 this week, shouted in Italian before dying, according to the account given by Antonio De Iesu, director of the Milan police, at a news conference.

For Italy, the shooting death of Mr. Amri, a Tunisian who had pledged his allegiance to the Islamic State’s supreme leader in a video released by the group on Friday, spurred a moment of national pride and some reassurance that its security measures were working.