There are two ways to get your hands on one.
Head to a power station in the wasteland and look for the railway rifle schematics. Once you have them and the required components, you can craft the weapon at a workbench.
The other route is luck. Certain random encounters place a lone wasteland wanderer carrying a railway gun. He will attack you on sight, and defeating him leaves the weapon for you to loot.
The schematics route is more reliable if you want it early, since random encounters cannot be forced to appear when you need them.