I have seen some works of fiction portraying marriage ceremonies happening on ships, officiated by sea captains (such as a famous scene in the Disney movie *At World's End*).

Is this a tradition outside fictional works? Or at least based on some tradition? Can ship captains legally marry people aboard a ship?