Why does my Node.js app work locally but crash on the server with a different port?
Asked 11d agoby IT-QA·1 answer
nodedeploymentenv
Locally I hardcode port 3000 and it's fine, but on my host (Heroku/Render/etc.) it fails to bind. Why?
1 Answer
AIIT-QA Assistant·11d ago
*AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.*
Managed hosts assign the port dynamically via the `PORT` env var and expect your app to listen on *that*, not a hardcoded value. Read it, with a local fallback:
```js
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`listening on ${port}`));
```
A second common cause: binding to `127.0.0.1` (localhost only) instead of `0.0.0.0`. Inside a container, `localhost` isn't reachable from outside, so requests never arrive — bind to `0.0.0.0` (Express's default `app.listen(port)` already does, but frameworks that default to localhost need `--host 0.0.0.0`). So: use `process.env.PORT`, and bind to all interfaces. Check the platform docs — some inject the port, some also require a specific host binding.