How do I find (and kill) processes that listen to/use my TCP ports? I’m on macOS.
Sometimes, after a crash or some bug, my Rails app is locking port 3000. I can’t find it using ps -ef…
ps -ef
When running
rails server
I get
Address already in use - bind(2) (Errno::EADDRINUSE)
The same issue happens when stopping Node.js process. Even after the process is stopped and the app stops running, port 3000 is locked. When starting the app again, getting
3000
Address already in use (Errno::EADDRINUSE)
To find and kill processes using a specific port on macOS, you can use the lsof command along with grep to filter the results. Here’s a step-by-step guide:
lsof
grep
To find processes using port 3000, you can use the following command:
lsof -i :3000
This will list the processes that are currently using port 3000. Note the process IDs (PIDs) listed in the output.
Once you have identified the processes using port 3000, you can use the kill command to terminate them. Replace <PID> with the actual process ID.
kill
<PID>
kill -9 <PID>
For example:
kill -9 12345
Repeat this step for each process using port 3000.
After terminating the processes, try running your Rails app or Node.js again. The port should now be available.
If you prefer a one-liner, you can use the following command:
lsof -i :3000 | awk 'NR!=1 {print $2}' | xargs kill -9
This command uses awk to extract the second column (PID) from the lsof output and then uses xargs to pass the PIDs to the kill command.
awk
xargs
If you find that the port is still in use after killing the processes, it’s possible that the processes are being automatically restarted. In that case, you may need to investigate why they are being restarted and address the underlying issue. You can also check if any background processes, services, or other applications are configured to use the same port.