How to find the process that is using a port
By Flavio Copes
Learn how to find which process is listening on a port using the lsof -i command, then stop it with kill so you can free up a busy port like 3000.
The lsof -i :PORT command tells you which process is listening on a port, along with its PID. Once you have the PID, you can stop the process with kill.
Sometimes when developing multiple applications at once, or trying out demos, I end up with multiple programs running on different ports on my computer: 3000, 3001, 1313, and so on.
If I don’t pay close attention, I might forget which application is running on a specific port.
The lsof command helps us find out. The name stands for “list open files”, and on macOS and Linux a network connection counts as an open file, so lsof can list those too.
The -i flag filters by network address. Running
lsof -i :1313
will tell me the command that’s currently listening on port 1313:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
hugo 8698 fla 4764u IPv4 0xc72ca30d18e45ef9 0t0 TCP localhost:bmc_patroldb (LISTEN)
In this case it’s the hugo command, with PID 8698.
Notice the NAME column says localhost:bmc_patroldb instead of localhost:1313. That’s because lsof translates known port numbers into service names. Add the -P flag to see the numeric port instead:
lsof -i :1313 -P
How do I stop the process?
If I want to terminate that program, I can just run kill 8698.
kill sends the TERM signal, which asks the process to shut down cleanly. Most dev servers respond to it right away.
If the process ignores it, you can force it with the KILL signal:
kill -9 8698
Use that as a last resort. The process gets no chance to clean up after itself.
You can also combine the lookup and the kill in one line. The -t flag makes lsof print only the PID, which is exactly what kill wants:
kill $(lsof -t -i :3000)
I use this one all the time when a dev server didn’t shut down properly and port 3000 is stuck.
When lsof prints nothing
Be careful: an empty result doesn’t always mean the port is free. Without extra privileges, lsof only shows processes owned by your user. If the port is taken by another user’s process, or by a system service, run it with sudo:
sudo lsof -i :3000
If that also prints nothing, the port really is free, and something else is causing your “address already in use” error.
Related posts about cli: