Explain Codes LogoExplain Codes Logo

How to fix Error: listen EADDRINUSE while using NodeJS?

javascript
error-handling
nodejs
port-management
Alex KataevbyAlex Kataev·Oct 10, 2024
TLDR

Handle the EADDRINUSE error by liberating the port or selecting a different one:

  • Liberate the port with kill after finding the conflicting process' PID using lsof:
lsof -i :PORT && kill -9 $(lsof -t -i :PORT)
  • Alternately, go for portfinder module for autoselection of an available port in Node.js:
const portfinder = require('portfinder'); portfinder.getPort((err, port) => { // Let's launch the server on `port`, Captain! });
  • Directly set a different port in your Node.js app when all else fails:
const PORT = 3001; // Let's give this one a shot, shall we? app.listen(PORT);

Settle on an approach that promptly fixes the snag, either by freeing the port or switching to an empty one.

Process conflict check

First things first, run the below command to monitor active processes possibly hogging the desired port.

sudo lsof -i tcp:PORT

If you stumble upon a sneaky process that doesn't belong, terminate it kindly with:

kill -15 PID

This broadcasts a SIGTERM, allowing the process to wave goodbye, clearing the port without causing collateral damage.

Managed port handling

Within your Node.js code, keep an ear out for the 'listening' event which confirms your server's successful deployment:

server.on('listening', () => { console.log(`Server is smoothly sailing on ${PORT}`); });

Also, flip unpleasant surprises like EADDRINUSE by using server.on('error'):

server.on('error', (error) => { if (error.code === 'EADDRINUSE') { console.error(`Port ${PORT} is on duty. Requesting backup...`); server.listen(++PORT); // If at first you don't succeed, try, try again } else { throw error; } });

Leveraging this pattern, your server can strive to nest on the next vacant port when it bumps into EADDRINUSE.

Diverse fixes and recommendations

  • Beyond trying an alternate port, contemplate exploiting Nginx as a reverse proxy. With this setup, you can even host a party with multiple applications on the same server sharing port 80.

  • Validate whether any protective barriers or system limitations could be barring your application from claiming the intended port.

  • While suppressing Node processes, opt for CTRL+C rather than 'kill -9'. This enables Node.js to depart peacefully and pass on the port.

  • Be vigilant for port-hungry applications like Skype. Adjust Skype's settings to dissuade it from occupying the port.

  • Wield utilities like nodemon or PM2 to supervise automatic reboot of your Node.js servers, outsourcing process management so you don't have to manually deal with PIDs.

  • When the going gets tough, the tough get going. Terminate stubborn pests with the mightier command:

sudo fuser -k PORT/tcp

Spotting the right processes

To filter through running processes spotted by ps ax, include a grep for node:

ps ax | grep node
  • Once you've found the culprit, gracefully exterminate it. Take care! Make sure you aren't halting vital system processes which could cause unexpected consequences.

Advanced strategies and considerations

  • Bear in mind that browsers interpret port binding differently than NodeJS. Test your application under diverse scenarios to guarantee stability.

  • Employ the 'net.createServer' function to keep track of server activity and network connections, providing a direct approach to manage EADDRINUSE in your code.