An off-duty NYPD sergeant on his way to work shot an ex-con who tried to rob him in Brooklyn early Thursday morning — and he has been placed on modified duty while the department investigates, police said.

The 40-year-old cop was walking to a nearby train station on Livonia Avenue near New Jersey Avenue in East New York around 5 a.m. when the man approached and allegedly pretended to have a gun in his pocket while he attempted to rob him, police sources told The Post.

“He was minding his business on his way to work, parks his car to take the train,” a law enforcement source said.

The cop, from the 109th precinct in Queens, fired two rounds, shooting the man once in the mouth, according to law enforcement sources.

The 21-year-old suspect was later determined not to be armed, police sources said.

“If you tell me you got a gun and you’re gonna rob me, I’m going to shoot your a–,” a police source said. “What am I supposed to do, wait for him to shoot me?”

He was taken in police custody to Brookdale Hospital Medical Center with life-threatening injuries, an FDNY spokeswoman said. His condition was downgraded to non-life-threatening, police said.

The man was released from jail in November after serving nine months for a having a loaded .9 mm firearm in Brooklyn, the source said.

He has nine previous arrests, including for robbery, gun possession and drug charges.

The cop was taken to an area hospital for ringing in his ears, police said. He was placed on modified duty as a result of the incident, police sources said.

“We are reviewing videos that are out there,” Chief Terence Monahan said, adding that there “may have been some dispute prior to this incident.”