Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
ctfrancia opened this issue Mar 27, 2019 · 47 comments
Closed

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

ctfrancia opened this issue Mar 27, 2019 · 47 comments

Comments

@ctfrancia
Copy link

ctfrancia commented Mar 27, 2019

Hey guys, so I have been just trying to start testing my Koa server using Supertest.

I am getting the error: Error: listen EADDRINUSE: address already in use :::3000

I have tried closing everything down on that port and run it but I'm still getting the issue.

Here is my app:

require('dotenv').config();
const Koa = require('koa');
const app = new Koa();
const router = require('./router');
const PORT = process.env.NODE_PORT || 3001;
const ENV = process.env.NODE_ENV || 'Development';
const logger = require('koa-logger');

app.use(logger());
app.use(router.routes());

app.listen(PORT, (err) => {
    if (err) console.error('❌ Unable to connect the server: ', err);
    console.log(`🌍 Server listening on port ${PORT} - ${ENV} environment`);
  });

    module.exports = app;

my router:

const Router = require('koa-router');
const router = new Router();

router.get('/', ctx => ctx.body = 'Sending some JSON');
  module.exports = router;

finally the test:

const server = require('../index');
const request = require('supertest').agent(server.listen());

afterEach(() => {
  server.close();
});

describe('routes: index', ()=> {
  it('should reach endpoint', async () => {
    const response = await request(server).get('/');
   
    expect(response.status).toEqual(200);
    expect(response.body).toEqual('Sending some JSON');
  });
});

my server isn't even running on port 3000 it is running on 8080
however, just to make sure I will run my server on 3000 and it starts up no problem. I then try to run the test, I get the error again with the server running on 3000 and the server not. Kinda stuck

@rimiti
Copy link
Contributor

rimiti commented Mar 27, 2019

Could you send us the output of:
lsof -i:3000

@ctfrancia
Copy link
Author

Hi @rimiti I don't get any output

@ctfrancia
Copy link
Author

UPDATE so the reason was because in my app.test.js file I had a series of tests that were not closing after completion because I was running tests like:

const app = require('../index');

describe('server working', () => {
  
  it('should exist', async (done)=> {
    expect(app).toBeDefined();
    done();
  });

  it('should be an object', async (done)=>{
    expect(typeof app).toBe("object");
    done();
  });
});

and I am still getting the error:

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue.

@aech12
Copy link

aech12 commented Jul 21, 2019

I had that exact error message, try this out:

Expected: I can use app.listen(PORT, ()=>{})

Code: index.js exports "app", app.listen(PORT, ()=>{}) is uncommented

Output: npm test => "Jest did not exit one second after the test run has completed.
This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue."

Workaround: comment/delete app.listen(PORT) and listen to the port on another file (example: require "app" from index.js in app.js and listen to a port in app.js)

@aech12
Copy link

aech12 commented Jul 21, 2019

what's weird is that the documentation claims "if the server is not already listening for connections then it is bound to an ephemeral port for you so there is no need to keep track of ports."

@ctfrancia
Copy link
Author

Ok thanks a lot, I will be checking that out for sure!

@dgreene1
Copy link

Looks like you have to do two things:

  1. ensure that the app has not yet been started (i.e. put the app.listen in an if statement that asserts it's not in test mode first)
  2. pass koa.callback() into supertest as follows:
request(app.callback())

@dionisoros
Copy link

lsof -i:3000 
kill -9 [PID] 

@Atabic
Copy link

Atabic commented Jan 9, 2020

You are actually running the main server in the terminal. Stop the server so the debugger can run on the same PORT

@spock123
Copy link

So I had this issue as well.
What you want to do is that you don't want to start your server. In your main server express file you should export the server. But do NOT call the listen method.

So modify your code so that when you're testing (for example by setting an environment variable and looking for that), you're not calling the listen() method. This should resolve it and let you run your tests in parallel.

@avencat
Copy link

avencat commented Feb 17, 2020

Thanks a lot @aech12 and @spock123 you saved my day!

@Robertosousa86
Copy link

Cheers from brazil, thank you all for the support!

@HashemDeveloper
Copy link

lsof -i:3000 
kill -9 [PID] 

What is PID here? New comer please help. Thank you.

@cguidog
Copy link

cguidog commented Mar 4, 2020

@HashemDeveloper when you run lsof -i:3000, you will get some information related to the port. the second column in the returned table says PID, that's what you have to type instead of [PID] when run kill -9

@HashemDeveloper
Copy link

@HashemDeveloper when you run lsof -i:3000, you will get some information related to the port. the second column in the returned table says PID, that's what you have to type instead of [PID] when run kill -9

I actually figured that out by try and error. Thank you for the reply though.

@Abdelrahmanyassin786
Copy link

im new to web development and i get the same error and dont know exactly what to do can someone please dumb it down for me

@cguidog
Copy link

cguidog commented Apr 13, 2020

@Abdelrahmanyassin786 In your terminal window, where you are running your application; run this command:
lsof -i:3000
It will return some information related to process running; look for the PID number.
next, run kill -9 [PID], but replace [PID] with the PID number from the first command.
That will kill the process completely, and you will be able to start it again.

@Abdelrahmanyassin786
Copy link

it tells me 1sof command is not found

@Abdelrahmanyassin786
Copy link

the thing is that my root route doesnt work but if i type for example /blog/new it opens fine

@cguidog
Copy link

cguidog commented Apr 13, 2020

@Abdelrahmanyassin786 It is not a number one it's the letter L

@Abdelrahmanyassin786
Copy link

still doesnt work
i wish i would know how to copy my terminal in here like you guys do so i could show you

@Abdelrahmanyassin786
Copy link

i tried sth i typed killall -9
then i did killall -u
then killall -v it worked but i honestly dont know which made it work

@JoeyHayfron
Copy link

So I had this issue as well.
What you want to do is that you don't want to start your server. In your main server express file you should export the server. But do NOT call the listen method.

So modify your code so that when you're testing (for example by setting an environment variable and looking for that), you're not calling the listen() method. This should resolve it and let you run your tests in parallel.

@spock123 please do you mean exporting the what i assign the express function to?
For instance
i have
const app = express();

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

module.exports = server;

Please do you mean i should export just app??

@MiraTechCoder
Copy link

Hey guys, so I have been just trying to start testing my Koa server using Supertest.

I am getting the error: Error: listen EADDRINUSE: address already in use :::3000

I have tried closing everything down on that port and run it but I'm still getting the issue.

Here is my app:

require('dotenv').config();
const Koa = require('koa');
const app = new Koa();
const router = require('./router');
const PORT = process.env.NODE_PORT || 3001;
const ENV = process.env.NODE_ENV || 'Development';
const logger = require('koa-logger');

app.use(logger());
app.use(router.routes());

app.listen(PORT, (err) => {
    if (err) console.error('❌ Unable to connect the server: ', err);
    console.log(`🌍 Server listening on port ${PORT} - ${ENV} environment`);
  });

    module.exports = app;

my router:

const Router = require('koa-router');
const router = new Router();

router.get('/', ctx => ctx.body = 'Sending some JSON');
  module.exports = router;

finally the test:

const server = require('../index');
const request = require('supertest').agent(server.listen());

afterEach(() => {
  server.close();
});

describe('routes: index', ()=> {
  it('should reach endpoint', async () => {
    const response = await request(server).get('/');
   
    expect(response.status).toEqual(200);
    expect(response.body).toEqual('Sending some JSON');
  });
});

my server isn't even running on port 3000 it is running on 8080
however, just to make sure I will run my server on 3000 and it starts up no problem. I then try to run the test, I get the error again with the server running on 3000 and the server not. Kinda stuck

i experience these problem
root of these problem :
is when i try to run my previous project i created and then i open the server(mix phx.server)
after i run and tried i just close the terminal(MINGW64/MSYS2 terminal) with out killing the running the server(which i don't know how to do it)
after these i create another project and running the server (mix phx.server)
then these problem occurs also in me

my solution to these: i restart my computer and run again then i find it running good again.

but my problem (how to kill the server with out restarting it)

@DrobyshevAlex
Copy link

Sometimes, when i press save and the server restarts i get the same error.

@abdennourzahaf
Copy link

abdennourzahaf commented Jun 30, 2020

I have the same problem and i couldn't understand what do @spock123 and @aech12 mean by exporting the server.
How can you export the server if you are not calling the listen() method, which returns the server object at the first place?
I am really confused, if you can provide a code snippet it would help.
NOTE: I am using --runInBand flag for the moment, it works but it slows down the testing.

@spock123
Copy link

module.exports = server;

Please do you mean i should export just app??

Yes! precisely!
You export just the app, but do not call listen()

@spock123
Copy link

I have the same problem and i couldn't understand what do @spock123 and @aech12 mean by exporting the server.
How can you export the server if you are not calling the listen() method, which returns the server object at the first place?
I am really confused, if you can provide a code snippet it would help.
NOTE: I am using --runInBand flag for the moment, it works but it slows down the testing.

Hi @zfnori
The server is an instantiation of your application. But only when you call the "listen" method, will it start listening for incoming request.

This means you can export that "server" object like any other variable.
Hope it makes sense.

@JoeyHayfron
Copy link

JoeyHayfron commented Jun 30, 2020 via email

@nirav7707
Copy link

I had that exact error message, try this out:

Expected: I can use app.listen(PORT, ()=>{})

Code: index.js exports "app", app.listen(PORT, ()=>{}) is uncommented

Output: npm test => "Jest did not exit one second after the test run has completed.
This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue."

Workaround: comment/delete app.listen(PORT) and listen to the port on another file (example: require "app" from index.js in app.js and listen to a port in app.js)

thankyou @aech12 your solution work for me

@MaciejKutynia
Copy link

I have the same issue, solution that I found is go to node_modules find nodemon/monitor/run. And there is variable "killedAfterChange" in my case var killedAfterChange = false; i changed to var killedAfterChange = true; and it's worked fine

@alforsii
Copy link

alforsii commented Mar 4, 2021

Hi everyon. I had this error:
Error: listen EADDRINUSE: address already in use 3001
The same as above. The problem was in my case colors npm package. I did attach color to the PORT before I passed to the app.listen, like :
const PORT = process.env.PORT.yellow || 5000;
Don't do this,instead use color extension in the console.log, like:
app.listen(PORT, () =>
console.log(
Server running in ${process.env.NODE_ENV.yellow} mode on port ${PORT.yellow}
)
);
Something like this. Hopefully, it helps someone. My issue was solved with this. Happy coding guys! 🙌

@GregPetropoulos
Copy link

I added an additional node and started the server on it and ran with out issues. I am guessing you cant run concurrently dev dependencies on the main node. Not sure why this worked but basically just click the plus sign on your vs code in the terminal to open a secondary node and run the app.

@GregPetropoulos
Copy link

Never mind that didn't hold up after rerunning the app. I found that my insomnia running on the same port as my app is conflicting as I check my routes

@chinedu360
Copy link

You are actually running the main server in the terminal. Stop the server so the debugger can run on the same PORT

simple yet very effective answer.

@vasilisliapis
Copy link

I had the same problem and instead of writing
afterEach(() => {
server.close();
});
I wrote
afterEach(async() => {
await server.close();
});
because server.close() returns a promise

@emercadogarcia
Copy link

lsof -i:3000 
kill -9 [PID] 

this is solution; tanks.

@hzlnqodrey
Copy link

lsof -i:3000 
kill -9 [PID] 

This worked for me. Thanks a lot.

@vladyslav-dev
Copy link

I had the same problem and the problem was that I wrote app.listen() two times ))))

@korovenko-tatyana
Copy link

Perhaps you have 2 projects and one with docker. Check "docker ps" - maybe you use this port. Then stop it.

@Dharmesh1981
Copy link

I had the same problem and just restart VS Code and the problem solved

@AlbertVilaCalvo
Copy link

AlbertVilaCalvo commented Sep 13, 2022

To fix this you need to avoid calling app.listen() when you run tests. There are 2 questions on StackOverflow with various solutions:

In summary, one solution is to wrap app.listen():

if (process.env.NODE_ENV !== 'test') {
    app.listen(port)
}

And another solution is to organize your code so that app.listen() is placed in a different file than app:

@area73
Copy link

area73 commented Dec 26, 2023

For anyone whos struggling with koa , vitest and supertest ,

After doing what @AlbertVilaCalvo said in his comment, you will need to also init supertest passing app.callback() like this:

import supertest from "supertest";
import { describe, expect, it } from "vitest";
import { app } from "../../app";

describe("hit endpoint", () => {
  const req = supertest(app.callback());
 ...

btw , no need to use afterEach, afterAll and so on to stop server

@Liskoooo
Copy link

Liskoooo commented Mar 8, 2024

Guys this none-sense took me about 2 days. I re-structured the code, because i had that double calling problem with the "app.listen()" method. I though that was finally it, but still no resolve. The problem is that I had test suites. And they run dynamically altogether. At some point during execution 2 different tests try to use the same port and BOOM, we got this error. Because you see, mostly the error appeared (EADDRINUSE), but sometimes it did not (I ran "npm test" like hundreds of times xD), so I couldnt wrap my head around it. So the solution is to change that default behaviour, to run test-suites SEQUENTIALLY, NOT in PARALLEL. So I just had to put "--runInBand" in scripts.jest :

"scripts": {
"jest": "jest --env=node --colors --coverage test --runInBand",
"test": "npm run jest --forceExit --detectOpenHandles --verbose --maxWorkers=1"
},

I also have other stuff in this "scripts. jest" object and "scripts.test", which I copied from all the potencial solutions in Stackoverflow and here Github. They didnt help, but I will just let them be. What solved my problem was purely "--runInBand".

@maheenur13
Copy link

maheenur13 commented Mar 15, 2024

I just figured a solution for windows.
Just added to function in my server.ts

import { exec } from 'child_process';
import net from 'net';

async function isPortInUse(port: number): Promise<boolean> {
  return new Promise<boolean>(resolve => {
    const tester: any = net
      .createServer()
      .once('error', () => resolve(true))
      .once('listening', () =>
        tester.once('close', () => resolve(false)).close()
      )
      .listen(port);
  });
}

async function killProcessOnPort(port: number): Promise<void> {
  return new Promise<void>((resolve, reject) => {
    exec(`netstat -ano | findstr :${port}`, (error, stdout) => {
      if (error) {
        reject(error);
        return;
      }
      const pidMatch = stdout.match(/\b(\d+)\r?\n?$/);
      if (pidMatch) {
        const pid = parseInt(pidMatch[1]);
        exec(`taskkill /PID ${pid} /F`, killError => {
          if (killError) {
            reject(killError);
          } else {
            resolve();
          }
        });
      } else {
        resolve(); // No process found using the port
      }
    });
  });
}
then all you need to call this these function in your `bootstrap()` like this: 
const isPortAvailable = await isPortInUse(Number(config.port));
    if (isPortAvailable) {
      await killProcessOnPort(Number(config.port));
    }
**Happy coding!**

@ms3byoussef
Copy link

"scripts": {
"test": "jest --watchAll --verbose --coverage --maxWorkers=1",
"start": " nodemon index.js",
}

that's work with me

@ahmeedev
Copy link

After couple of tries, i found i put a semicolon " ; " at the end of variable value in the .env file.. just remove the semicolon.. and it will work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests