go back

How to end a process by port number

Nov 18, 2023

Have you ever tried to start a service in your Node.js environment, only to discover that something is already running on the desired port?

You might have saw an error like Error: listen EADDRINUSE: address already in use :::5000 and wondered what to do next.

If so, I have a solution for you! There is an incredibly useful Node.js package called kill-port that allows you to kill a process on a given port.

Using the kill-port package

It's super easy to use. All you have to do is run the following command:

npx kill-port 5000

That's it! Now you can start your service on port 5000. I should mention that this isn't the only way to end a process by port number, but the npx command is quite convenient as it doesn't require you to install anything globally. I've seen it fail on rare occasions, and in those cases, I had to terminate the process another way. But in my experience, it works most of the time! ๐Ÿคฃ

npx kill port success

What if kill-port doesn't work? ๐Ÿค”

If you do run into a situation where kill-port doesn't work, you can look up how to terminate a process by port number on your operating system. I won't go into the specifics here, but the key takeaway is: if kill-port doesn't work, there are always alternative methods to terminate the process!

...and if I want to see which process is running on that port before terminating it? ๐Ÿ˜Ÿ

Naturally, you might want to see which process is running on a given port before you terminate it. If so, you can use the following commands to see which process is running on a given port.

MacOS

lsof -i :5000

Windows

netstat -ano | findstr :5000

Just replace 5000 with the port number you want to check. This can be especially useful in development environments where multiple services might be running simultaneously.

go back