Skip Main Navigation
Ben IlegboduBen Ilegbodu

Easily kill a process running on a port

How to use the kill-port package with npx to stop the process running on a given port

Sunday, October 18, 2020 ยท 1 min read

Generally when I try to run a web server on an existing port, it will tell me that the port is already in use and ask if I want to use another one:

Something is already running at port 8080
? Would you like to run the app at another port instead? โ€บ (Y/n)

But sometimes, usually for older servers, when the port is in use I'll get an error like:

Fatal error: Port 8080 is already in use by another process.

Typically this error simply means that I have to stop a duplicate server. But recently I was having problems with Gatsby not completely shutting down when I stopped the server. So even though the web server technically wasn't running, the port was still in use. And I had no idea how to kill the process running on the port.

So naturally I googled for a solution and found a relevant Stack Overflow question. It told me to run the lsof command and combine it with the kill command in order to kill the process:

kill $(lsof -t -i:8080)

So I did that the first time. And honestly I wasn't sure if I was opening a backdoor for someone to use my machine to mine Bitcoin. ๐Ÿ˜‚

But the next time I needed to kill a process running on a port, I had to google again to find that same Stack Overflow question. My command line skills are improving day-by-day, but there's no way I'm going to be able to remember that command.

Luckily I stumbled upon an npm package, kill-port, that does exactly what I need with a much friendlier interface. And thanks to npx, I don't even have to install it. I just run:

npx kill-port 8080

That's it! It's slower than the kill + lsof because npx has to temporarily install the kill-port package. But it's 1000x times easier for me to remember. I took a peak at the source code for kill-port and under the hood the package is using kill + lsof of course! The kill-port package is just providing a more approachable abstraction in my opinion.

Keep learning my friends. ๐Ÿค“

Subscribe to the Newsletter

Get notified about new blog posts, minishops & other goodies

โ€‹
โ€‹

Hi, I'm Ben Ilegbodu. ๐Ÿ‘‹๐Ÿพ

I'm a Christian, husband, and father of 3, with 15+ years of professional experience developing user interfaces for the Web. I'm a Google Developer Expert Frontend Architect at Stitch Fix, and frontend development teacher. I love helping developers level up their frontend skills.

Discuss on Twitter // Edit on GitHub