remy / nodemon

Monitor for any changes in your node.js application and automatically restart the server - perfect for development
http://nodemon.io/
MIT License
26.29k stars 1.73k forks source link

Error: listen EADDRINUSE: address already in use :::5000 #1849

Closed tiagosalema closed 3 years ago

tiagosalema commented 3 years ago

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.

remy commented 3 years ago

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.

tiagosalema commented 3 years ago

This is the repo where I am running it.

server.js roughly looks like this:

const app = express();

connectDB(); // mongoose

// Routes...

// serve static assets in production (React app)
if (['production', 'ci'].includes(process.env.NODE_ENV)) {
  app.use(express.static('client/build'));
  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, '..', 'client', 'build', 'index.html'));
  });
}

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
remy commented 3 years ago

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.

roshennair commented 3 years ago

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:

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.

roshennair commented 3 years ago

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"
    }
  3. 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.

roshennair commented 3 years ago

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...

AlaaMouch commented 3 years ago

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...

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: ```typescript export class HttpEntrypoint { // ... start(): Promise { 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 ```
sahilrajput03 commented 3 years ago

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

roshennair commented 3 years ago

@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. 😂

tiagosalema commented 3 years ago

@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

sahilrajput03 commented 3 years ago

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

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)

What os are you using, i am using popos latest that is based on ubuntu 20.04 lts.

wisnshaftler commented 3 years ago

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 :-(

sahilrajput03 commented 3 years ago

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 ..?

emko commented 3 years ago

i get port in use also and i am running on linux, is there any way to make nodemon wait for the process to close before it tries to run a new one?

emko commented 3 years ago
process.on("SIGUSR2", () => {
  console.log("server shutting down");
  setTimeout(() => {
    console.log("hello?");
  }, 5000);
});

[nodemon] restarting due to changes...
Server shutting down
[nodemon] starting `node ./bin/www`
Port 3020 is already in use
[nodemon] app crashed - waiting for file changes before starting...
hello?

see the hello? message showing up from first process while nodemon already tried running the process again before it.

shouldn't this cause nodemon to have to wait? as the process is still running? also in the example of nodemon trying to use once instead of on doesn't work since nodemon sends the SIGUSR2 twice and the second one just causes the code not to finish running at all.

i don't know if this helps or i am doing something wrong. i was thinking to do server.close() and delay the process.exit but it seems like nodemon just opens another process before this one closes.

remy commented 3 years ago

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)

moadgeek commented 3 years ago

In case you're in windows try to 'End task' for all node.js processes (What worked for me), if you are on Linux then use this command: _kill $(lsof -t -i:PORT) Replace PORT with the one you have your server running in.

trdaya commented 3 years ago

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.

aadi3124 commented 2 years ago

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");

SantiagoRokstars23 commented 2 years ago

reinicia la pc bro

kritisharma99 commented 1 year ago

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

Siehan commented 1 year ago

I replaced PORT 5000 with another PORT: 3000 and it worked straight away.

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

at processTicksAndRejections (node:internal/process/task_queues:83:21) {

code: 'EADDRINUSE', errno: -48, syscall: 'listen', address: '::', port: 5000 } [nodemon] app crashed - waiting for file changes before starting... [nodemon] restarting due to changes... [nodemon] starting node server.js AI server started on http://localhost:3000

fcan26 commented 1 year ago

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

fcan26 commented 1 year ago

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

Garrett96 commented 1 year ago

Yep. Confirming this is an AirPlay issue if you use MacOS. It's using port 5000 by default.

Open a new terminal tab and enter: lsof -i tcp:5000 and you might see ControlCe.

Turning off AirPlay receiver is just one click in the settings, didn't need to restart or anything.

Kind of a weird error lol

Credits to this post

timurbuch commented 1 year ago

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

This is the one! Saving me from a ton of headaches!

1314ivan commented 1 year ago

my problem was solved by using an explicit host on mac os

app.listen(+port,'localhost', () => {
  console.log(`app start http://localhost:${port}`)
})

and off “AirPlay Receiver” in the “Sharing” System Preference

coolcreation commented 5 months ago

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 ..?

Clearing the cache worked wonders for me- thanks so much!