The striker put Girona ahead with a powerful header in the 12th minute, after a fine cross from Miguel Gutierrez, whom Madrid sold to the Catalan club in the summer.
His second goal came 12 minutes later after he beat Eder Militao to a long ball and fired past Andriy Lunin, who played in goal for Madrid after Thibaut Courtois was affected by a stomach bug.
Vinicius Jr pulled a goal back for Real Madrid, which was at close to full strength, in the 34th minute, but Castellanos completed his hat-trick early in the second half after a cross from Ivan Martin, and he netted his fourth of the game in the 62nd minute with another unstoppable header.
Lucas Vazquez netted a late consolation for Real Madrid, but the result once again highlights how Carlo Ancelotti's side is focused on Europe and the Copa del Rey, although the coach apologized for the display in his post-game press conference.
Fourth-placed Real Sociedad had to withstand a lot of pressure in the second half away to fifth-place Betis, but held on for a draw that keeps them six points clear of their nearest rival for a place in next season's UEFA Champions League.
The visitors had the best of the first half, but Betis reacted well, and Sergio Canales was inches away from a winner, only for his shot to go just over the bar.
Betis could slip to seventh depending on Villarreal and Athletic Club Bilbao's results on Thursday.
Osasuna won 1-0 away to Cadiz, heightening the home side's relegation worries. Both teams had chances in the game, but Ruben Garcia's 62nd-minute shot from outside the area sent the points back to Pamplona, while Cadiz could drop into the bottom three before the end of the week if results go against them.
Barcelona could move 14 points clear of Real Madrid if they win away to Rayo Vallecano on Wednesday, while Atletico Madrid can move to within two points of Real Madrid if they win at home to Mallorca.