Kill already running ports with ease

ยท 1 mins read ยท ย Workflow

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 to List 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 the PID (process id) we are looking for
  • | is used to pass the list of PID we found, to the next command
  • xargsis used to apply kill to each of these PID
  • kill is actually killing each PID. We might need to use kill -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.


Did you like this one?

I hope you really did...

Buy Me A Coffee


Get notified about latest posts and updates once a week!!


Buy Me A Coffee