nodemon: Error: listen EADDRINUSE: address already in use :::5000

  • nodemon -v: 2.0.7
  • node -v: 14.16.01
  • Operating system/terminal environment: MacOS Big Sur
  • Using Docker? No
  • Command you ran: nodemon server

Expected behaviour

Close port before reinitializing server.

Actual behaviour

[0] [nodemon] starting `node server.js`
[0] events.js:292
[0]       throw er; // Unhandled 'error' event
[0]       ^
[0] 
[0] Error: listen EADDRINUSE: address already in use :::5000
[0]     at Server.setupListenHandle [as _listen2] (net.js:1318:16)
[0]     at listenInCluster (net.js:1366:12)
[0]     at Server.listen (net.js:1452:7)
[0]     at Function.listen (/Users/tf/Documents/courses/MERN/server/node_modules/express/lib/application.js:618:24)
[0]     at Object.<anonymous> (/Users/tf/Documents/courses/MERN/server/server.js:35:5)
[0]     at Module._compile (internal/modules/cjs/loader.js:1063:30)
[0]     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
[0]     at Module.load (internal/modules/cjs/loader.js:928:32)
[0]     at Function.Module._load (internal/modules/cjs/loader.js:769:14)
[0]     at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
[0]     at internal/main/run_main_module.js:17:47
[0] Emitted 'error' event on Server instance at:
[0]     at emitErrorNT (net.js:1345:8)
[0]     at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  code: 'EADDRINUSE',
[0]   errno: -48,
[0]   syscall: 'listen',
[0]   address: '::',
[0]   port: 5000
[0] }
[0] [nodemon] app crashed - waiting for file changes before starting...

Steps to reproduce

  1. Initialize app (basic MERN app)
  2. Save any file.
  3. Error is thrown.

This only started happening after I updated my Mac to Big Sur. I can circumvent this issue by either stopping the app and killing the port or by saving a second time a couple of seconds after the first crashed the server.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 5
  • Comments: 28 (3 by maintainers)

Most upvoted comments

Okay, start striping the code back until you have the bare minimum and you can still replicate, then post that here, then we can take a look.

I’ve found a temporary work-around, the steps for which are listed below:

  1. Install the NPM kill-port package as a development dependency: npm install -D kill-port
  2. Create a new file in your project’s root directory called nodemon.json and paste in the following JSON (edit the port numbers below from 3000 to whatever port you’re using for your Node.js app):
{
	"events": {
		"restart": "kill-port 3000",
		"crash": "kill-port 3000"
	 },
	"delay": "1500"
}
  1. Add the following NPM script to your package.json file (if you haven’t already):
"scripts": {
	"dev": "nodemon app.js",
},

All credit goes to Tudor Constantin on Stack Overflow. However, it is a bit tedious and definitely a workaround, not something that should be done for all future Node.js projects.

@tiagosalema , I was having same problem and i restarted my system and its fixed now. Wow, that was easy to fix 🤣

I’ve recently started facing the same issue on my own application. Nodemon was working fine all this while but now seems to be leaving a single Node process listening on an open port (3000, in my case). I looked up past issues on the GitHub repo and found that the most popular one had been closed last year.

My stripped-down entry file (app.js) looks like this:

const express = require('express');

const app = express();

app.listen(3000, () => console.log('listening on port 3000...'));

app.get('/', (req, res) => res.send('Home'));

As for other environment and version info:

  • Node.js: v15.14.0
  • Nodemon: 2.0.7
  • Express: 4.17.1
  • OS: Ubuntu 20.04.2 LTS on Windows 10 (WSL 2)

Right now, I’m forced to manually kill the running process myself and restart the Node server, which defeats the purpose of using Nodemon at all. Any help is appreciated.

if you use MacOS turn off “AirPlay Receiver” in the “Sharing” System Preference

In case anyone is still facing this issue even after killing the PID, just restart your machine. Seemed to fix it for me. Weird fix, I’m sure the issue is on nodemon’s side.

I’ve recently started facing the same issue on my own application. Nodemon was working fine all this while but now seems to be leaving a single Node process listening on an open port (3000, in my case). I looked up past issues on the GitHub repo and found that the most popular one had been closed last year. My stripped-down entry file (app.js) looks like this:

const express = require('express');

const app = express();

app.listen(3000, () => console.log('listening on port 3000...'));

app.get('/', (req, res) => res.send('Home'));

As for other environment and version info:

  • Node.js: v15.14.0
  • Nodemon: 2.0.7
  • Express: 4.17.1
  • OS: Ubuntu 20.04.2 LTS on Windows 10 (WSL 2)

Right now, I’m forced to manually kill the running process myself and restart the Node server, which defeats the purpose of using Nodemon at all. Any help is appreciated.

Facing same issue. If we have to restart everything by killing previous session then what is use of nodemon

if you use MacOS turn off “AirPlay Receiver” in the “Sharing” System Preference

@tiagosalema , I was having same problem and i restarted my system and its fixed now. Wow, that was easy to fix 🤣

Lmao the same thing happened to me, I just didn’t write about it because I didn’t think it was replicable. The old “Have you tried turning it off and on again?” worked for me too. 😂

basic MERN app

Can you explain and provide example code? Because I’m pretty sure “basic” actually means: set up mongodb, add nginx, possibly webpack and a bunch others. i.e. not compatible with “basic”.

If you can provide code that replicates this issue, happy to look at it. Otherwise this is too vague.

i already have this issue. im using express mongodb joi

nodemon

it happened two times first time i try delete and re install all node modules and it not work. i try restating my PC several times and its not working then i totally uninstall nodejs and re install it. That time it works correctly

after few days now (2021/5/9 10:29PM ) its show this error again 😦

Correction: The method I’ve shown above provides inconsistent results, and shouldn’t be considered a fix. It only works half of the time, and also occasionally crashes when Nodemon restarts.

Back to the drawing board…

reinicia la pc bro

hi, I am quite new in nodejs and express, getting this error and not finding any solution. Please help me. thanks!

C:\D\PlayBox\back_end\middlewares\auth.js:41
    return res.sendStatus(401).send("Invalid Token");
               ^

TypeError: Cannot read properties of undefined (reading 'sendStatus')
    at Object.verifyToken (C:\D\PlayBox\back_end\middlewares\auth.js:41:16)
    at C:\D\PlayBox\back_end\app.js:70:21
    at Layer.handle [as handle_request] (C:\D\PlayBox\back_end\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\D\PlayBox\back_end\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\D\PlayBox\back_end\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\D\PlayBox\back_end\node_modules\express\lib\router\layer.js:95:5)
    at C:\D\PlayBox\back_end\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\D\PlayBox\back_end\node_modules\express\lib\router\index.js:341:12)
    at next (C:\D\PlayBox\back_end\node_modules\express\lib\router\index.js:275:10)
    at jsonParser (C:\D\PlayBox\back_end\node_modules\body-parser\lib\types\json.js:119:7)
[nodemon] app crashed - waiting for file changes before starting...

#This is my code#

function verifyToken(req, res, next) {
  let token = req.body.token || req.query.token || req.headers["authorization"];
  token = token.split(" ")[1];

  console.log(">>>>>token   " + token);
  if (!token) {
    return res.send(403, "A token is required for authentication");
  }
  try {
    const decoded = jwt.verify(token, "process.env.ACCESS_TOKEN_SECRET");
    req.user = decoded;
  } catch (err) {
    return res.sendStatus(401).send("Invalid Token");
  }
  return next();
}

getting error in this line >>> return res.sendStatus(401).send(“Invalid Token”);

This issue is being a little hijacked!

I can tell folks that the example supplied still isn’t parred down enough - this version (because it’s actually running on a different system which and is due to an entirely different problem). I get that it’s hard to pare down - but it has to happen to be able to first replicate which allows way for a fix.

For those on windows the issue you were facing has been fixed in 2.0.9.

I’m going to close this issue because the follow on posts have the same vague symptom but don’t answer those prerequisite questions specifically about OS.

In addition, the original OP, @tiagosalema hasn’t been able to recreate using the example repo and jumping through the whole setup:

Screenshot 2021-06-30 at 18 42 26

node @ v14.15.1 nodemon @ 2.0.9 (a couple of bump, but specific to windows)

i already have this issue. im using express mongodb joi

nodemon

it happened two times first time i try delete and re install all node modules and it not work. i try restating my PC several times and its not working then i totally uninstall nodejs and re install it. That time it works correctly

after few days now (2021/5/9 10:29PM ) its show this error again 😦

Try this… npm cache clean --force, and see if nodemon works after that …?

@tiagosalema , I was having same problem and i restarted my system and its fixed now. Wow, that was easy to fix 🤣

Your system as in computer? I’ve tried a few different things to no avail, including

  • restarting the project
  • restarting the computer
  • deleting and reinstalling all node_modules
  • assigning the port as an environment variable instead of assigning it in the app (a stackoverflow answer suggested that)

I came across variants of this issue many times without ever being able to replicate it deterministically. But on all cases, I have found that…

  • Killing the port-process ${port} on the nodemon events start, restart or crash, does not solve my problem.
  • Synchronously killing it right before calling .listen(...) on my express app does not solve my problem.
  • However, asynchronously killing it before calling .listen(...) in a .then() does solve my problem, when…
    • …either fuser -k ${port}/tcp and npx kill-port ${port} is used to kill the port-process.
    • …the nodemon restart is delayed (hint: to delay it, merge your current nodemon.json with {delay: ${milliseconds}}). I have the solution below running almost all of the times with {delay: "500"}.

I have written a brief code snippet that does the job of killing the conflicting port-process at run-time, using fuser. I don’t think adapting the code so as to use npx kill-port ${port} would be very hard: I would appreciate if anyone could augment my code with that adaptation 😃

Basically, one call of killPort keeps killing all the port-processes that hold onto the port ${port} until no processes are left. Finally, an interval is set so that if a round of killPort has killed any process, it checks again after some time. This killing and re-killing was done because for some reason the conflicting port-processes would get killed once but the error EADDRINUSE would still show up. It may be overkill, pun intended, but to be honest, it works, and I’m happy because of that.

Here it is, along with my current use case and its output:

import {execSync} from 'child_process';

const buildKillPortPromise = (port: number) => new Promise(
    (resolve) => {
      const killPort = () => {
        let hasKilled = false;
        while (true) {
          const pid = execSync(
              `fuser -k ${port}/tcp || echo '---'`, // fuser exits with 1 when no process has been killed
              {stdio: ['ignore', 'pipe', 'ignore']}, // https://nodejs.org/api/child_process.html#child_process_options_stdio
          ).toString().trim();
          if (pid !== '---') {
            hasKilled = true;
            console.log(`PID ${pid} was holding onto port ${port}. It was killed.`);
          } else {
            return hasKilled;
          }
        };
      };
      const intervalId = setInterval(() => {
        if (!killPort()) {
          clearInterval(intervalId);
          resolve(undefined);
        }
      }, 500); // this is the minimum that I have found that works consistently
    },
);
Use case:
export class HttpEntrypoint {
  // ...
  start(): Promise<void> {
    return this.setup() // this.app.use(morgan('combined')) and other stuff
        .then(() => buildKillPortPromise(this.config.port))
        .then(
            () => new Promise(
                (resolve) => {
                  this.server = this.app.listen(
                      this.config.port,
                      () => resolve(undefined),
                  );
                },
            ),
        )
        // .then(() => console.log(`Started listening at ${port}`));
        // ^ this goes outside of this class:
        // await entrypoint.start().then(() => console.log(...))
  }
}
Output:
> nodemon

[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): src/**/*
[nodemon] watching extensions: ts
[nodemon] starting `ts-node src/index.ts`
Started listening on 8420
[nodemon] restarting due to changes...
[nodemon] starting `ts-node src/index.ts`
PID 19286 was holding onto port 8420. It was killed.
Started listening on 8420
[nodemon] restarting due to changes...
[nodemon] starting `ts-node src/index.ts`
PID 19391 was holding onto port 8420. It was killed.
Started listening on 8420
[nodemon] restarting due to changes...
[nodemon] starting `ts-node src/index.ts`
PID 19485 was holding onto port 8420. It was killed.
Started listening on 8420
[nodemon] restarting due to changes...
[nodemon] starting `ts-node src/index.ts`
PID 19663 was holding onto port 8420. It was killed.
Started listening on 8420
[nodemon] restarting due to changes...
[nodemon] starting `ts-node src/index.ts`
PID 19834 was holding onto port 8420. It was killed.
Started listening on 8420
[nodemon] restarting due to changes...
[nodemon] starting `ts-node src/index.ts`
PID 19942 was holding onto port 8420. It was killed.
Started listening on 8420