C-3PO was created by Anakin to help his mother around the house, but when Anakin married Padme then 3PO became her servant. After Padme died he became a protocol droid working for Bail Organa and the Rebel Alliance. Bail was Leia's adoptive father so that's why he was aboard her ship. He escaped with the Death Star plans along with R2-D2 and became property of the Lars family, who were the step-aunt-and-uncle to Luke, which is how Luke became 3PO's master, but by the time of The Force Awakens he was working as a spymaster for Leia in the Resistance.
Earth doesn't matter in Star Wars. It takes place "a long time ago in a galaxy far, far away". Humans are just a populous species in that galaxy. All those other ones are aliens.