小能豆

Find (and kill) process locking port 3000 on Mac

javascript

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

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

Address already in use (Errno::EADDRINUSE)

阅读 92

收藏
2023-12-25

共1个答案

小能豆

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:

1. Find Processes Using a Specific Port:

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.

2. Kill the Processes:

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 -9 <PID>

For example:

kill -9 12345

Repeat this step for each process using port 3000.

3. Retry Running Rails or Node.js:

After terminating the processes, try running your Rails app or Node.js again. The port should now be available.

One-Liner to Kill Processes on Port 3000:

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.

Additional Note:

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.

2023-12-25