“As mayor, this is something I never wanted to live through,” Fredericton’s leader, Mike O’Brien, said at a news conference. “We will get through this together.”

The two officers were responding to a report of gunshots in a residential area of Fredericton, the provincial capital, when they came upon two bodies, Deputy Police Chief Martin Gaudet said at a news conference. The officers were killed as they approached the victims, he said.

A number of other people were taken to hospitals, including the gunman, who was seriously injured. Officials would not disclose the nature of any of the injuries, or how they were incurred. The assailant was identified only as 48-year-old local man.

The shootings, followed by a two-hour lockdown in the surrounding neighborhood, shocked many in this city of about 60,000. Gun violence is rare in Fredericton, and homicides all but nonexistent: The last one occurred in 2014.

Many found themselves startled to be thrust into a national debate about gun crime — something usually connected to larger cities, like Toronto, which is still reeling from a shooting rampage last month.

But once news spread that two of the victims were police officers, there was also a sickly sense of déjà vu. In 2014, a gunman hunted down police officers in nearby Moncton, killing three of them and wounding two.

On Friday in Fredericton, the police would not discuss a possible motive for the shooting or the type of gun used. The investigation, said Deputy Chief Gaudet, was being handed over to the Fredericton branch of the Royal Canadian Mounted Police.

Robert DiDiodato, who lives near the shooting scene, said that he was reading and drinking coffee shortly before 7 a.m. when he heard several loud gunshots outside. He stepped out of his house to investigate and heard shots again.

“It was a bang and a bang, then bang, bang, bang,” Mr. DiDiodato said.

Mr. DiDiodato said that police officers, some armed with assault rifles, swarmed a small apartment building in the area. He said he could see officers shielding residents while evacuating them from their homes.

“I found it quite impressive,” he said. “It just struck me that they had the evacuees between them and the building where the shooter was.”

For about two hours on Friday morning, the police advised neighbors to stay inside and lock their doors. Officers shut down a four-mile stretch of road.