The blaze burned for nearly 24 hours after cars went off the tracks Saturday at a tunnel entrance near Keene, a small town about 15 miles east of Bakersfield.
Seven homes in Keene were evacuated and the residents of 30 others were advised to stay indoors with the windows closed for most of the day Sunday, said Kern County Fire Department Engineer Justin Corley.
Two cars from the long Burlington Northern Santa Fe Corp. freight train ran off Union Pacific tracks on the well-known Tehachapi Loop.
Three train cars carrying alcohol, plastic pellets and cornmeal caught fire, and the blaze spread into the tunnel, making it very difficult to put out, Corley said.
Corley said the car carrying plastic was "putting out a heavy, dark smoke" that made for dangerous conditions and brought the evacuation of everything in a 2-mile radius.
The cause of the blaze remained under investigation, and railroad officials were examining the tunnel for structural damage, Corley said.
The train was bound for Stockton from Barstow, BNSF spokeswoman Lena Kent said.
Firefighters were assisted by the Kern County Environmental Health Agency, the Kern County Sheriff's Department and the California Highway Patrol.