Make Node.js listen on the right port

2 min read07 November 2026

An app can look online at the process level and still be unreachable if it listens on the wrong port or interface. On app hosting, the public port is assigned by the platform: your code must read it from the environment and listen on all interfaces, never on a hard-coded number.

Read the provided port

The platform exposes the port in PORT. Read it at startup, convert it to a number and listen on 0.0.0.0:

JavaScript
const http = require('http');

const port = Number(process.env.PORT || 3000);
if (!Number.isInteger(port) || port <= 0) {
  console.error('Invalid PORT');
  process.exit(1);
}

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('ok');
});

server.listen(port, '0.0.0.0', () => {
  console.log(`listening on port ${port}`);
});

0.0.0.0 means "all IPv4 interfaces". With 127.0.0.1, the process only accepts local connections and the platform proxy cannot reach it. On Linux, :: listens on IPv6 and often accepts IPv4 too in dual-stack mode, but 0.0.0.0 remains the explicit choice for this kind of hosting.

Common errors

Symptom Likely cause Fix
EADDRINUSE Two processes on the same port Stop the old one, restart cleanly
EACCES Port below 1024 Use the provided port
"Online" but unreachable Listening on 127.0.0.1 Listen on 0.0.0.0
ERR_SOCKET_BAD_PORT Missing or non-numeric PORT Validate at startup, fail clearly
Restart loop Exception before listen Read the first error in the log

An EADDRINUSE on managed hosting often means a second listen() call in the code, or an old instance still running. On a VPS you can identify the owner with ss -ltnp | grep :3000 (adjust the number); root is required to see every process.

Do not hard-code the port

The port can change if the service is recreated or its allocation changes. listen(3000) works locally and fails on redeploy day, which makes the incident hard to tie back to configuration. Use the same variable for internal URLs your app generates, such as a password reset link.

Never trust a port supplied by the client in a request: a user must not be able to redirect your server to another interface. The listen port comes from the environment, not from an HTTP header.

Check

  1. Restart and look for the listening line in the console.
  2. Test the URL or allocation shown in the panel, not localhost from your machine.
  3. Send a simple request:
Bash
curl -i http://ADRESSE_FOURNIE:PORT/
  1. If the process runs but the request fails, check the listening interface first, then platform routing, then your application logic.

Advertisement

Was this article helpful?

Read next