Kill already running ports with ease
One of the most annoying things during development is the moment we face the following error in command line while trying to launch an application locally:
Server Error: this port is already in use
Most of the times this means that we have forgotten a process running in the background or that we thought that we killed a process but we actually didn't, since we didn't use CTRL + C
to kill it the right way etc
This is probably the moment that most developers start searching around the web to find a solution so the marathon for copy-n-pasting random commands in terminal begins ๐
# A common approach
On a Linux / Mac machine, this might save the day for you:
lsof -ti tcp:[PORT] | xargs kill
Let's break this into steps to understand some more what is going on here:
lsof
is used toList Open Files
so we can spot processes that listen on a specific port-i
is used to search for the wanted port-t
is used to return only thePID
(process id) we are looking for|
is used to pass the list ofPID
we found, to the next commandxargs
is used to applykill
to each of thesePID
kill
is actually killing eachPID
. We might need to usekill -9
if processes need to be killed by force
But, who can memorize all these, right? ๐ฌ
# An easier approach
Let's see an even more straightforward solution we can use:
# One port
npx kill-port [PORT]
# Multiple ports
npx kill-port [PORT1] [PORT2] [PORTN]
Easier, right? By doing so, we pull the npm package kill-port
so it can do the dirty work for us.
It is far more declarative and self-explanatory so it is definitely easier to remember.
Cheers!!
Did you like this one?
I hope you really did...
Newsletter
Get notified about latest posts and updates once a week!!
You liked it?