Like so many concepts in psychology, this harmful behavior arises from mundane causes. Human beings are cognitive misers - this means that they save their mental energy for the times when it is really needed, and spend the rest of the time on a sort of auto-pilot. They create categories (schema) to quickly represent both people and objects. There's no need for you to figure out how a chair works each time you encounter a new one, because you have a cognitive representation of that object that tells you what it is and how it works. In fact, when you learn, you engage in two simple processes: generalizing, which means group things that are similar together, and discriminating, which means separating things that are different from other things. Remember Sesame Street?
This simple game played with children teaches them how to generalize and discriminate. We also notice when people are different from us, which is a form of discriminating (not discrimination - yet).
Because our brain is built to put people and objects into easy categories, this can make us likely to start applying certain characteristics to those categories of people. If we're not careful, these can become stereotypes - beliefs about the behavior or thoughts of a certain group. Stereotypes can lead to prejudice, which is an inflexible and incorrect (and usually negative) attitude toward a certain group. Finally, prejudice can lead to discrimination, which is a behavior toward a certain group.
I do want to mention that by explaining the "lineage" of discrimination, I'm in no way excusing it. Instead, I think that by understanding the natural ways these attitudes, beliefs, and behaviors arise, we can take steps to prevent prejudice and discrimination. Obviously it takes work, because it often requires people to think in the opposite way to which they are inclined. For instance, some prejudice interventions ask people to look for commonalities between themselves and the out-group, essentially recategorizing people so that your out-group is now part of your in-group. Increased contact with the out-group can also decrease prejudice. (I'll be blogging later in April about both of these interventions, because they involve some of the most influential research in social psychology - so stay tuned!)