Castellanos recorded his first career hat trick and posted his first career four-point game as NYCFC (11-8-3, 36 points) scored at least four goals for the third time this season and improved to 5-0-1 in the last six home meetings with the Red Bulls (8-9-5, 29 points).
The Red Bulls dropped seven points behind NYCFC in the Eastern Conference standings, as the Blues sit in fifth place still fighting for a home-field game or two in the playoffs.
After an active first half left the teams in a 2-2 tie, Alexander Ring scored the tiebreaking goal in the 51st minute off a throw-in from Jesus Medina. Ring finished off the play with a booming left-footed shot that sailed over goalkeeper Ryan Meara's head, off the crossbar and into the net.
Castellanos had opened the scoring by converting a nifty header with his back to the net after getting a long cross from Maximiliano Moralez in the 12th minute. Six minutes later, Brian White scored for the Red Bulls from about 18 yards out when his right-footed shot eluded a diving Sean Johnson.
Cristian Casseres gave the Red Bulls a short-lived 2-1 lead in the 38th when his shot deflected into the net off NYCFC defender Maxime Chanot. Gary Mackay-Steven knotted the game just four minutes later by taking a deft pass from Castellanos in the 42nd minute, eluding Tim Parker and Casseres and sliding the ball into the net just before Kyle Duncan could defend the play.
That made it 2-2, and it was all about the Blues from there.
After Ring gave NYC the lead, Castellanos padded the lead in the 76th minute when he quickly flipped a pass from Medina into the net. And in the 84th minute, he converted a penalty kick to complete the fourth regular-season hat trick in club history.
Castellanos joined David Villa (2017) as the second NYCFC player to score a hat trick against the Red Bulls.
Meara allowed a career-high five goals as the Red Bulls' five-game unbeaten streak ended. It was the first time the Red Bulls have allowed five goals by NYCFC.
Sean Johnson stopped three shots for NYCFC.