Gastly is apart of the Captain's Pokémon team who won the Orange Island League over 300 years ago.
The captain met his demise when a bad storm sank his pirate near Moral Island and the wreckage remained undisturbed until a couple of deep sea divers located the ship and scavenged the Orange Island League trophy which was placed in a museum.
Gastly and Haunter awakened from their Pokéballs and rose the ship above the water to search for the Orange Island trophy and replace it back inside the ship as a tribute to their late master.