This is a great question, and it's not as simple many comments here make it seem to be. This Veritasium video has a great explanation (and an enormous ball of molten sodium).
In case of Earth, Wikipedia describes [1] it as being "[..] generated by electric currents due to the motion of convection currents of a mixture of molten iron and nickel in Earth's outer core". This makes Earth a geodynamo [2]. (The aforementioned Wikipedia page is actually really long and detailed, a lot more than I would have thought)