The derailleur is the device that changes gears by moving the chain from one sprocket to another. There are two derailleurs: one on the rear and one on the front. The highest ratio (when the bike can go fastest) is produced when the chain is on the biggest sprocket in the front and the smallest in back. The lowest ratio (the bike is easiest to pedal up hills, but very slow) is produced when the chain is on the smallest sprocket in front and the biggest in back.
The rear derailleur has two main tasks: keep the chain tense and switch gears.
The rear derailleur adjusts its position to maintain tension in the chain no matter which gear you are in. If the chain is on the biggest sprocket in front and in back, more of the chain is wrapped around sprockets and the derailleur has less slack to deal with. If the chain is on the smallest sprockets in the front and back, the derailleur has more slack to deal with.
The rear derailleur switches gears by moving the bottom of the chain from side to side. When you pedal the bike, the top of the chain is in tension -- the force of your legs pedaling pulls it tight. It is this part of the chain that transmits the force from the front sprockets to the rear sprockets. The bottom of the chain is kept in light tension by the rear derailleur. Since the bottom of the chain is not under much load, the derailleur can move the chain to another sprocket even if you're pedaling hard.
Sprocket technology has improved the ability of bikes to shift under load. The sprocket in the picture above is one of the nine sprockets in the rear. Some of the teeth are shorter and wider than others -- these teeth grab the chain first during a shift and pull it up onto the sprocket. The sprocket also has "ramps," special grooves in the side that help pull the chain onto the sprocket.
The front derailleur moves the chain between the three front sprockets. Unlike the rear derailleur, the front derailleur moves the top part of the chain, which is under tension when you are pedaling. This means that in order to switch sprockets on the front, you have to ease off on the pedals.
Some front sprockets also employ a clever design to allow shifting under load. The sprocket in the photo below is the center of the three front sprockets. Notice the small pegs sticking out from the side of the sprocket -- these pegs catch the chain and pull it up onto the sprocket. Like the rear sprockets, this front sprocket has ramps that help pull the chain up.
Now let's see how all those gears are used.