The Argentine centre-forward had a day to remember as he became the first man to net four goals against Madrid in La Liga since 1947.
The last player to score four goals against Madrid was Robert Lewandowski with Borussia Dortmund in the Champions League in 2013.
The result means that Barcelona can now open a 14-point gap on Los Blancos as they inch closer to the La Liga title.
Castellanos opened the scoring with a close-range header in the 12th minute past an outstretched Andriy Lunin. He netted his second after outpacing Madrid centre-back Eder Militao.
Vinicius Jr halved the deficit, but Castellanos netted twice in the second half to make it 4-1. Lucas Vazquez grabbed a later goal for Madrid but they were well beaten.
Castellanos said: “It’s been a dream night, for the four goals and the victory against a rival of such an entity.
“Without the help of my colleagues and the people who always support me, today would have been impossible.”
This campaign is Castellanos’ first season in Europe. He had joined Girona from Major League Soccer club New York City FC.
He won the 2021 MLS Golden Boot with 19 goals in 32 games. He is the second youngest player to hit 50 MLS goals.
The 24-year-old took his La Liga tally to 11 goals with the four strikes against the 14-time Champions League winners.
- Postecoglou confirms huge injury blow for Tottenham ahead of Crystal Palace clash
- FA Cup quarter-final TV picks confirmed, ITV will show headline fixture between Man Utd and Liverpool
- Preview: Man City vs Man United – stats, team news, line-ups
- Crystal Palace shareholder John Textor slams Premier League financial rules
- Conor Gallagher determined to stay at Chelsea despite contract stand-off and Tottenham interest
- Eric Dier makes permanent switch to Bayern Munich from Tottenham
- Premier League manager of the month nominees for February revealed
- Paul Pogba receives four-year ban for doping
- Man United fans in uproar as Old Trafford relocation plans spark outrage
- Liverpool to make one last attempt to bring back Michael Edwards to lead post-Klopp rebuild