When the planets were first forming, they were orbiting within a disc of gas, and while inside that disc, they can actually slide around and adjust their orbits to their neighbors until they're perfectly in tune.