Danny Fox
Danny Fox

Reputation: 40699

How to fix Error: listen EADDRINUSE while using NodeJS?

If I run a server with the port 80, and I try to use XMLHttpRequest I am getting this error: Error: listen EADDRINUSE

Why is it problem for NodeJS, if I want to do a request, while I run a server on the port 80? For the webbrowsers it is not a problem: I can surf on the internet, while the server is running.

The server is:

  net.createServer(function (socket) {
    socket.name = socket.remoteAddress + ":" + socket.remotePort;
    console.log('connection request from: ' + socket.remoteAddress);
    socket.destroy();
  }).listen(options.port);

And the request:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
    sys.puts("State: " + this.readyState);

    if (this.readyState == 4) {
        sys.puts("Complete.\nBody length: " + this.responseText.length);
        sys.puts("Body:\n" + this.responseText);
    }
};

xhr.open("GET", "http://mywebsite.com");
xhr.send();

Upvotes: 550

Views: 915657

Answers (30)

zemil
zemil

Reputation: 5066

If you use docker image with nodejs just stop container:

  • to get nodejs CONTAINER_ID
docker ps
  • and stop it
docker stop CONTAINER_ID
  • or if you use docker compose
docker compose stop nodejs_service_name

Upvotes: 0

Muhammed Aslam C
Muhammed Aslam C

Reputation: 57

Actually you are trying to run on a port thats actually taken up by some other services (usually other webservers like apache, iis etc)

  1. Figure out which service is using the port

  2. Stop it and restart node server

Or go for another port like 8080,5000...

For windows

netstat -ano -p tcp |find "80"

For linux

 sudo lsof -i -P -n

Upvotes: 0

Patrick Suzuki
Patrick Suzuki

Reputation: 57

It's also useful to look into what process is using the port.

For macOS I found out from this article that AirPlay uses Port 5000 so even if you kill it using the solutions listed here, it will take-up Port 5000 again. Do a quick Google search to see what common apps or processes are using the port that is causing the error.

Upvotes: -2

karnveersingh
karnveersingh

Reputation: 131

Steps to resolve it -:

1: need to kill the process with following command.

pm2 kill <PROCESS_ID>

2: restart the service again with following command:

pm2 start app.js --name "servername"

3: check the status of the server with following command.

pm2 list

Upvotes: 0

Adam Gonzales
Adam Gonzales

Reputation: 948

In ZSH, when I typed exit, I noticed a message stating: zsh: you have suspended jobs.

  1. Type the word jobs, hit enter
  2. Type kill %1 (where %1 is the number of the job), hit enter
  3. Response should state terminated {job_name}

I found the answer here

Upvotes: 0

Bruce Seymour
Bruce Seymour

Reputation: 1598

NOOB ERROR FIX: I'm new to Node.js and setup a webserver listening to port 8080. I ran into the EADDRINUSE error. I tried all the various 'kill -9 node' iterations and kept getting, 'node: no process found'

The problem was, I was calling http.listen(8080); TWICE in the same blob of code. So the first time it was actually working fine, and the second time it threw an error.

If you're getting a 'no process found' response when trying to kill the port, try checking to make sure you're only opening the port once.

Upvotes: 1

BanAnanas
BanAnanas

Reputation: 522

I got:

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

I was trying to look for the process listening to port 8000
and had no luck - there were none
(sudo netstat -nlp | grep 8000 ).

It turned out I had app.listen(8000) written twice in my script.

My assumption is that the interference was happening only in a short time when trying to run the script, so looking for processes listening to the port before and after error didn't show any.

Upvotes: 6

WasiF
WasiF

Reputation: 28847

Error reason: You are trying to use the busy port number

Two possible solutions for Windows/Mac

  1. Free currently used port number
  2. Select another port number for your current program


1. Free Port Number

Windows

1. netstat -ano | findstr :4200
2. taskkill /PID 5824 /F

enter image description here

Mac

You can try netstat

netstat -vanp tcp | grep 3000

For OSX El Capitan and newer (or if your netstat doesn't support -p), use lsof

sudo lsof -i tcp:3000

if this does not resolve your problem, Mac users can refer to complete discussion about this issue Find (and kill) process locking port 3000 on Mac


2. Change Port Number?

Windows

set PORT=5000

Mac

export PORT=5000

Upvotes: 43

Jee Mok
Jee Mok

Reputation: 6556

There is a way to terminate the process using Task Manager:

Note that this solution is for Windows only

  1. Go to the Task Manager (or using the shortcut Ctrl + Shift + Esc)

  2. On "Background Processes", find "Node.js" processes and terminate them (Right-click them and choose "End Task")

enter image description here

  1. Now you should be able to start again

Upvotes: 8

Pramod Jain
Pramod Jain

Reputation: 462

lsof -i:3000;
kill -9 $(lsof -t -i:3000);
// 3000 is a your port
// This "lsof -i:3000;" command will show PID 
kill PID 
ex: kill 129393

Upvotes: 20

Javier Cobos
Javier Cobos

Reputation: 1182

Under a controller env, you could use:

pkill node before running your script should do the job.

Bear in mind this command will kill all the node processes, which might be right if you have i.e a container running only one instance, our you have such env where you can guarantee that.

In any other scenario, I recommend using a command to kill a certain process id or name you found by looking for it programmatically. like if your process is called, node-server-1 you could do pkill node-server-1.

This resource might be useful to understand: https://www.thegeekstuff.com/2009/12/4-ways-to-kill-a-process-kill-killall-pkill-xkill/

Upvotes: 32

Rob Evans
Rob Evans

Reputation: 6968

Just a head's up, Skype will sometimes listen on port 80 and therefore cause this error if you try to listen on port 80 from Node.js or any other app.

You can turn off that behaviour in Skype by accessing the options and clicking Advanced -> Connection -> Use port 80 (Untick this)

Turn off Skype port 80 usage

P.S. After making that change, don't forget to restart Skype!

Upvotes: 63

cocomatt
cocomatt

Reputation: 131

This happened to me because I had my server running in another Terminal window. Closing the connection solved the problem.

Upvotes: 1

Sidharth Srivastava
Sidharth Srivastava

Reputation: 607

EADDRINUSE means port of your nodejs app is already in use.

  • Now you have kill the process/app running on that port.
  • Find the process id of app by:

lsof -i tcp:3000

  • Now u will get process id from this.
  • Run this:

kill -9 processId

Upvotes: 5

Anupam Maurya
Anupam Maurya

Reputation: 2201

Try both commands and it will stop all node process.

killall 9 node
pkill node
npm start 

Upvotes: 9

In below command replace your portNumber

sudo lsof -t -i tcp:portNumber | xargs kill -9

Upvotes: 7

Tarakeswararao Marla
Tarakeswararao Marla

Reputation: 337

sudo kill $(sudo lsof -t -i:80)

for force kill

sudo kill -9 $(sudo lsof -t -i:80)

use above cmd to kill particular port and then run your server

Upvotes: 9

Michael Davidson
Michael Davidson

Reputation: 537

Got this error when we accidentally had two local Express environments in the same instance pointing to the same port.

If you got this far down this list of answers, I hope this will be helpful and solve your problem.

Upvotes: 0

trqhien
trqhien

Reputation: 792

This works for me (I'm using mac). Run this command

lsof -PiTCP -sTCP:LISTEN

This's going to display a list of ports that your syetem is using. Find the PID that your node is running

COMMAND     PID          USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
node      17269 hientrq   16u  IPv6 0xc42959c6fa30c3b9      0t0  TCP *:51524 (LISTEN)
node      17269 hientrq   19u  IPv4 0xc42959c71ae86fc1      0t0  TCP localhost:1337 (LISTEN)

and run kill -9 [YOUR_PID]

Upvotes: 19

Birol Efe
Birol Efe

Reputation: 1751

Seems there is another Node ng serve process running. Check it by typing this in your console (Linux/Mac):

ps aux|grep node

and quit it with:

kill -9 <NodeProcessId>

OR alternativley use

ng serve --port <AnotherFreePortNumber>

to serve your project on a free port of you choice.

Upvotes: 2

Rahul Makhija
Rahul Makhija

Reputation: 609

I had the same issue recently.

It means that the port is already being used by another application (express or other software)

In my case, I had accidentally run express on 2 terminals, so exiting the terminal using 'Ctrl + C' fixed things for me. (Run server from only one terminal)

Hope it helps others.

Upvotes: 2

Aaditya Chakravarty
Aaditya Chakravarty

Reputation: 123

EADDRINUSE translates to "The port you are trying to issue app.listen() on is being used by other programs". You can use a script like this to check if your port is in use and then change the port in your app.listen().

var net = require('net');
var errors = ['EADDRINUSE'];    
var isUsed = function(port) {
    var tester = net.createServer()
        .once('error', function (err) {
          if (!errors.includes(err.code)) {
           console.log("Port is in use, change the port.");
          }
        })
        .once('listening', function() {
            tester.once('close', function() { 
                console.log("You are good to go."); 
            })
            .close()
        })
        .listen(port);
}

You can add other errors in the errors array to check for all sorts of error types as well.

Upvotes: 0

SMshrimant
SMshrimant

Reputation: 709

I would prefer doing

killall -15 node

because, kill -15 gives process a chance to cleanup itself. Now, you can verify by

ps aux | grep node

Note: If you don't give process a chance to finish what it is currently doing and clean up, it may lead to corrupted files

Upvotes: 1

Chotala Paresh
Chotala Paresh

Reputation: 566

In my case Apache HTTP Server was run on port 80 I solved it by issue the command as root

sudo killall httpd

Update

If Jenkin is installed and running on your Mac;

  1. You can check it with sudo lsof -i tcp:8080
  2. If Yes, and You want to stop Jenkins only once, run: sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist

Upvotes: 3

Thavaprakash Swaminathan
Thavaprakash Swaminathan

Reputation: 6976

EADDRINUSE means that the port(which we try to listen in node application) is already being used. In order to overcome, we need to identify which process is running with that port.

For example if we are trying to listen our node application in 3000 port. We need to check whether that port is already is being used by any other process.

step1:

$sudo netstat -plunt |grep :3000

That the above command gives below result.

tcp6       0      0 :::3000                 :::*                    LISTEN      25315/node

step2:

Now you got process ID(25315), Kill that process.

kill -9 25315

step3:

npm run start

Note: This solution for linux users.

Upvotes: 12

Benny Code
Benny Code

Reputation: 54782

The error EADDRINUSE (Address already in use) reports that there is already another process on the local system occupying that address / port.

There is a npm package called find-process which helps finding (and closing) the occupying process.

Here is a little demo code:

const find = require('find-process')

const PORT = 80

find('port', PORT)
.then((list) => {
  console.log(`Port "${PORT}" is blocked. Killing blocking applications...`)
  const processIds = list.map((item) => item.pid)
  processIds.forEach((pid) => process.kill(pid, 10))
})

I prepared a small sample which can reproduce the EADDRINUSE error. If you launch the following program in two separate terminals, you will see that the first terminal will start a server (on port "3000") and the second terminal will close the already running server (because it blocks the execution of the second terminal, EADDRINUSE):

Minimal Working Example:

const find = require('find-process')
const http = require('http')

const PORT = 3000

// Handling exceptions
process.on('uncaughtException', (error) => {
  if (error.code === 'EADDRINUSE') {
    find('port', PORT)
      .then((list) => {
        const blockingApplication = list[0]
        if (blockingApplication) {
          console.log(`Port "${PORT}" is blocked by "${blockingApplication.name}".`)
          console.log('Shutting down blocking application...')
          process.kill(blockingApplication.pid)
          // TODO: Restart server
        }
      })
  }
})

// Starting server
const server = http.createServer((request, response) => {
  response.writeHead(200, {'Content-Type': 'text/plain'})
  response.write('Hello World!')
  response.end()
})

server.listen(PORT, () => console.log(`Server running on port "${PORT}"...`))

Upvotes: 3

ranjith
ranjith

Reputation: 414

Your application is already running on that port 8080 . Use this code to kill the port and run your code again

sudo lsof -t -i tcp:8080 | xargs kill -9

Upvotes: 18

prakash tank
prakash tank

Reputation: 1267

The option which is working for me :

Run:

ps -ax | grep node

You'll get something like:

 8078 pts/7    Tl     0:01 node server.js
 8489 pts/10   S+     0:00 grep --color=auto node    
 kill -9 8078

Upvotes: 1

rawel
rawel

Reputation: 3033

For windows users execute the following command in PowerShell window to kill all the node processes.

Stop-Process -processname node

Upvotes: 2

Tom Stickel
Tom Stickel

Reputation: 20391

For other people on windows 10 with node as localhost and running on a port like 3500, not 80 ...

What does not work:

killall    ?  command not found
ps -aux | grep 'node'     ?     ps:  user x unknown 

What shows information but still not does work:

 ps -aef | grep 'node'
 ps ax
 kill -9 61864

What does work:

Git Bash or Powershell on Windows

  net -a -o | grep 3500   (whatever port you are looking for) 

Notice the PID ( far right )
I could not get killall to work... so

  1. Open your task manager
  2. On processes tab , right click on Name or any column and select to include PID
  3. Sort by PID, then right click on right PID and click end task.

Now after that not so fun exercise on windows, I realized I can use task manager and find the Node engine and just end it.

FYI , I was using Visual Studio Code to run Node on port 3500, and I use Git Bash shell inside VS code. I had exited gracefully with Ctrl + C , but sometimes this does not kill it. I don't want to change my port or reboot so this worked. Hopefully it helps others. Otherwise it is documentation for myself.

Upvotes: 2

Related Questions