If you’re a web programmer, you’ve probably been there.
You’re chugging along in the coding process, running a server on one of your localhost ports. At some point you’re ready to take a break, or maybe you decide you’re done for the day, so you close the terminal… and then you realize.
Phooey! You forgot to close the server and it’s still running on that port!
Unfortunately, the way to find and kill that process is not super obvious. Fortunately, it is pretty easy once you know what you’re doing. All it takes is a little knowledge of the Bash.
But before we get to that, a disclaimer: This only applies to Mac and Linux (including Windows Subsystem for Linux). If you’re running stuff via the Windows command prompt, this is not the blog post you’re looking for.
OK, on to the solution!
First, open the terminal. Type
lsof -i:[port number] and hit enter. For example, if you were running the server on localhost:3000, you’d type
lsof command tells the terminal to “list open files,” including the processes that opened them. That would be an incredibly long and confusing list, though, so
-i allows you to specify the port (or “IP socket”) you’re looking for.
By typing this command first, you can confirm that the process you wanted to kill is in fact what’s running on that port. You generally don’t want to be killing random processes if you don’t know what they’re for.
kill $(lsof -t -i:[port number]) to actually kill the process and free up the port, using whatever port number you’re trying to target.
This command has two parts. The inner part in parentheses is finding the process like we did earlier, except the
-t flag formats the data in a way that can be used by the outer part of the command,
kill. That does exactly what it sounds like: it kills the process.
lsof -i:[port number] again if you want to confirm that the process was in fact killed.
Feel free to check out the documentation for lsof if you’re interested in learning more about this command and how it works.