How to find (and kill) processes listening to a port on Mac ?

To find and kill processes listening to a specific port on macOS, follow these steps:

1. Find the Process ID (PID) Using the Port

Use lsof (List Open Files) to identify the process:

lsof -i :<PORT>

Example (check port 8080):

lsof -i :8080

Output:

COMMAND  PID   USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
node    1234  alice   22u  IPv6 0xabcd...      0t0  TCP *:http-alt (LISTEN)
  • PID = 1234 (process ID)
  • COMMAND = node (process name)

2. Kill the Process

Use the kill command with the PID:

kill -9 <PID>  # Forceful termination (SIGKILL)

Example:

kill -9 1234

Alternative (use process name):

killall <COMMAND_NAME>  # e.g., killall node

One-Liner (Find and Kill)

Combine steps 1 and 2 into a single command:

lsof -ti :<PORT> | xargs kill -9
  • -t: Returns only PIDs.
  • xargs: Passes the PID to kill.

Example:

lsof -ti :8080 | xargs kill -9

Notes

  1. Permission Issues: Use sudo if the process is owned by another user:
   sudo lsof -i :<PORT>
   sudo kill -9 <PID>
  1. Check if the Port is Free:
   lsof -i :<PORT>  # No output means the port is free.
  1. Common Ports:
  • 3000 (React/Node.js)
  • 8080 (HTTP Alt)
  • 5432 (PostgreSQL)

Example Workflow

  1. Find the PID for port 3000:
   lsof -i :3000
   # Output: PID 5678 (node)
  1. Kill the process:
   kill -9 5678
  1. Verify:
   lsof -i :3000  # No output = success!

Why Use -9 (SIGKILL)?

  • SIGKILL forcibly terminates the process (no cleanup).
  • Use kill <PID> first (sends SIGTERM for graceful shutdown).
  • If the process ignores SIGTERM, escalate to kill -9.

Leave a Reply

Your email address will not be published. Required fields are marked *