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 tokill.
Example:
lsof -ti :8080 | xargs kill -9
Notes
- Permission Issues: Use
sudoif the process is owned by another user:
sudo lsof -i :<PORT>
sudo kill -9 <PID>
- Check if the Port is Free:
lsof -i :<PORT> # No output means the port is free.
- Common Ports:
3000(React/Node.js)8080(HTTP Alt)5432(PostgreSQL)
Example Workflow
- Find the PID for port
3000:
lsof -i :3000
# Output: PID 5678 (node)
- Kill the process:
kill -9 5678
- Verify:
lsof -i :3000 # No output = success!
Why Use -9 (SIGKILL)?
SIGKILLforcibly terminates the process (no cleanup).- Use
kill <PID>first (sendsSIGTERMfor graceful shutdown). - If the process ignores
SIGTERM, escalate tokill -9.