This custom evolved from the centuries-old practice of "manning the yards." Long ago, men aboard sailing ships stood evenly spaced on all the yards and gave three cheers to honor a distinguished person.
Now, men and women are stationed along the rails of a ship (or along the edge of the flight deck for big deck aviation ships) when honors are rendered to the President, the heads of a foreign state, or a member of a reigning royal family. Men and women so stationed do not salute. Navy ships will often man the rails when entering a port, or when returning to the ship's homeport at the end of a deployment.