Ships will self repair anywhere, but they will do so much faster when in orbit on a planet. Repair time varies considerably, but are generally proportional to the number of HP the ship is missing. Repair rates can change due to anomalies, a trade good, etc, but a ship missing 20 points will finish repairing itself twice as fast as one missing 40 points.
Repairs are usually free, but if you have a seriously damaged ship it can often be worthwhile to upgrade it. Build a second design that is essentially the same ship, and upgrade the damaged ship to the alternate design and you get a 1 turn complete repair (upgrae time may vary, depending on where the ship is).