NYPD cops killed a thug who opened fire on them early Friday shortly after he blasted a man in a drug- and gang-related shooting in Queens, authorities said.

The suspect, identified by law enforcement sources as 27-year-old Stephen Gillard, shot a 26-year-old man several times in the torso outside the Sanahy Deli & Grocery bodega on Sutphin Boulevard near Shore Avenue in Jamaica at around 1:45 a.m., police officials said.

The victim was taken to Jamaica Hospital Medical Center in critical condition.

Video surveillance of the shooting gave cops a clear look at the gunman, who they say knew his victim.

And about a half-hour later, two undercover officers in an unmarked car spotted a man who fit the description of the suspect sitting on a bench near Brinkerhoff Avenue and 156th Street.

As the officers, who were wearing body cameras, were turning their car around, he “immediately opened fire on their vehicle,” Police Commissioner James O’Neill told reporters Friday.

“Our two cops showed the utmost bravery and professionalism, exiting their vehicle, engaging the suspect and returning fire,” the city’s top cop said. “That’s the dedication to service we see every day from NYPD cops.”

Gillard, who was shot in the head, was taken to Jamaica Hospital Medical Center where he was pronounced dead, cops said. The officers involved were taken to Long Island Jewish Hospital for evaluation.

A 9mm handgun was recovered at the scene.

NYPD Chief of Department Terence Monahan said that the suspect fired two shots, while cops returned around eight shots.

One resident who awoke from the commotion said he initially thought he heard “fireworks” as the bullets rang out.

“But then we saw lots of police running down the block,” the man said. “There was one or two shots, then there was a delay … a few seconds later there were more shots … boom, boom, boom.”

“It was scary,” the man said.

According to Monahan, the suspect was “involved in some drug dispute and gang-related activity around that bodega” and “he may be involved in some other acts of violence just a week and a half ago.”

Police have made previous crack and cocaine busts at the bodega where the initial shooting unfolded, said Monahan, who added, “We believe this is an ongoing dispute from over there.”

Gillard had two prior arrests on his record — one for turnstile jumping in 2016 and one for criminal possession of a loaded firearm in 2010, according to police.

Additional reporting by Tina Moore and Kevin Fasick