Market LiveNIFTY25,263.8-0.14%SENSEX82,192.3+0.34%Gold 24K ₹12,098.38/g down302.9Silver ₹146.46/g down5.43
InsightforGeeks
Technology

Fix Node.js "Error: listen EADDRINUSE: address already in use" (Linux, macOS, Windows)

Sobin Mathew
20 Mar 2023
2 min read
Share:

You start your Express or Node.js server and see this:

Error: listen EADDRINUSE: address already in use :::3000

It means something is already listening on that port. Usually it is an earlier run of your own app that never shut down. Here is how to find it, stop it, and stop it happening again.

Linux and macOS: find the process

sudo lsof -i :3000
# or, on Linux
sudo ss -ltnp | grep 3000

The output shows the program name and its PID (process ID). Replace 3000 with your own port.

Stop it

kill <PID>

A plain kill asks the process to exit cleanly, so try it first. Only if it ignores you, force it with kill -9 <PID>. To do both steps at once:

lsof -ti :3000 | xargs kill

Windows

netstat -ano | findstr :3000
taskkill /PID <PID> /F

The PID is the last column of the netstat output.

Common causes

  • A forgotten terminal. The old node process is still running in another window or in the background.
  • nodemon or ts-node leftovers. A crashed watcher can leave a child process holding the port.
  • PM2. Run pm2 list. The app may already be running under PM2, so use pm2 stop <name> rather than starting it again.
  • Docker. A container may publish the port. Check with docker ps.
  • Another program such as a different dev server uses the same default port.

Avoid the clash in your code

Read the port from an environment variable so you can change it without editing code:

const port = process.env.PORT || 3000;
const server = app.listen(port, () => console.log(`Listening on ${port}`));

server.on("error", (err) => {
  if (err.code === "EADDRINUSE") {
    console.error(`Port ${port} is already in use`);
    process.exit(1);
  }
  throw err;
});

Also close the server cleanly when the process is told to stop, so the port is released:

for (const sig of ["SIGINT", "SIGTERM"]) {
  process.on(sig, () => server.close(() => process.exit(0)));
}

Quick fix: use another port

PORT=3001 node app.js

This works for a quick test, but find out what holds the original port so the problem does not return.

Tags:#nodejs#EADDRINUSE#express#kill server
Found this helpful? Share it with friends & colleagues
Share:
Sobin Mathew Verified Editorial Staff

Covering financial markets, commodity rates, and practical technology insights for India. Researched and fact-checked in accordance with our Editorial Policy.

Published on 20 March 2023General Information · Disclaimer

Recommended based on your reading interest

More in Technology