There are two main theories for why the heated matches between local sports teams is referred to as a derby:
1) Like the English horse race The Derby, it's named after the 12th Earl of Derby - who lent his name both to the equestrian contest, and a local rugby match between Wigan and St. Helens.
In terms of popular sports like soccer, it's most likely that the rugby game was the original inspiration for the phrase.
2) The second theory is that the name comes from a traditional football match involving the entire town of Ashbourne in Derbyshire. The game was so wild that it often resulted in fatalities.
I like this theory better - as it reflects the electric atmosphere that's created when two rival sports teams meet.
You may also be interested to know that the term 'derby' is used to describe matches between local rivas in several European countries. For example, in Italy the Derby della Madonnina is the name given to league encounters between AC Milan and Inter.
However, in the US the term "cross-town rivalry" is more commonly employed.