The following error can be encountered when running multiple servers:
> Error: Address already in use
> Error: listen EADDRINUSE
This is because the port has already been bound to a running server and now another server is trying to listen on that port.
There are 2 things that can be done:
- Start your server on a different port.
- Or free the port by killing the process associated with it.
Warning: If you choose the 2nd option, make sure you’re not killing anything important.
Getting the pid
Use lsof
to get the process id (pid) associated with the port:
$ lsof -ti :<PORT> # replace <PORT> with the port number
Killing the pid
To kill the process associated with the port:
$ kill $(lsof -ti :<PORT>) # replace <PORT> with the port number
There may be a scenario where you’ll need to pass the SIGKILL
signal to stop and kill the process immediately:
$ kill -9 $(lsof -ti :<PORT>)
Use sudo
if you don’t have permissions:
$ sudo kill -9 $(lsof -ti :<PORT>)
And Unix users can accomplish the same thing with fuser
:
$ fuser -k <PORT>/tcp # replace <PORT> with the port number