How to Fix Node.js Port and 502 Errors in cPanel
When a Node.js app on cPanel returns a 502 error or complains about a port, the cause is nearly always the same: the app is trying to control the port itself, when cPanel's Passenger environment expects to manage that for it. Once you understand that, the fix is straightforward.
Why the port causes trouble
In a normal Node setup you might write app.listen(3000). But under cPanel's Passenger, the platform assigns the port and passes it to your app through an environment variable. If your code hard-codes a port instead, Passenger and your app disagree, and you get a 502 because nothing is listening where expected.
The fix: listen on the environment port
Have your app listen on the port Passenger provides, falling back to a default only for local development. In practice that means using process.env.PORT rather than a fixed number. This lets the same code run locally and on cPanel without changes.
Step-by-step
- Open your app's main file (the startup file set in Setup Node.js App).
- Change your listen call to use the environment's port with a sensible fallback.
- Save, then restart the app from the Node.js App interface in cPanel.
Other things to check for a 502
- The startup file is correct — it must point to the file that starts your server.
- Dependencies are installed — run
npm installin the app directory. - The app is actually running — check its status; a crash on startup produces a 502. Read the app log for the error.
For general 502 troubleshooting beyond Node, see fixing the 502 Bad Gateway error.
Frequently asked questions
My app runs locally but 502s on cPanel.
That is the classic hard-coded-port problem. Locally your chosen port is free; on cPanel Passenger assigns a different one. Switch to the environment-provided port and restart the app.
I fixed the port but still get 502.
Then the app is likely crashing on startup. Check the application log for the real error — a missing dependency or a bad startup file is common — and confirm you restarted the app after changes.
Do I need to open a port in the firewall?
No. With the cPanel Node.js tool, Passenger handles the connection; you should not open ports manually. Let the platform manage it and simply listen on the port it provides.
Was this article helpful?