The Earth’s magnetic field results from the movement of molten metal in the Earth’s core. The outer core actually. It’s mostly molten iron, which conducts electricity, and as it convects up and down, like boiling water in a pot, the moving electrical charges create the Earth’s magnetic field. Its a bit like a dynamo.
What drives the convection of the outer core? The heat released from the freezing of the liquid metal to the solid inner core. The inner core is ever expanding, and the outer core is getting smaller and smaller. Ultimately, when the entire outer core freezes the Earth’s magnetic field should disappear. But we’ve got some hundreds of millions of years left so we don’t have to worry quite yet.
The Other Planets
The question came up: Do Mars and the other planets have magnetic fields?
Astronomynotes has compiled a table of Planet Atmospheres and Magnetic Fields that shows that of the inner planets — Mercury, Venus, Earth and Mars — only the Earth has a significant magnetic field; Mercury does have its own field but it has less than 1% the strength of the Earth’s.
At present, Mars does not have a magnetic field, but it does have remnant magnetism imprinted on its rocks, indicating that it used to have one in the past. It’s internal dynamo died away long ago. Interestingly, the pattern of Mars’ remnant magnetism indicates that it’s interior was once molten enough that the surface had tectonic plates just like the Earth.
On the other hand, the outer planets have much larger magnetic fields; Jupiter’s is almost 20 times larger than Earth’s. The gas giants’ magnetic fields are also generated by fluid motion in their interiors (Stevenson, 1983 (pdf)). It’s likely, however, that in some of these bigger planets, at least, the electrically conductive fluid is not liquid metal like in the Earth’s core, but either liquid hydrogen, or a water solution with dissolved electrolytes.