How to kill a process on a port on ubuntu ?

To terminate a process using a specific port on Ubuntu, follow these steps and examples:

Step 1: Find the Process ID (PID) Using the Port

Use one of these commands to identify the PID:

Using lsof

sudo lsof -i :<PORT>
# Example for port 8080:
sudo lsof -i :8080

Output:

COMMAND  PID   USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
node    1234  user   12u  IPv4 12345   0t0  TCP *:8080 (LISTEN)

Using ss (Socket Statistics)

sudo ss -tulnp | grep :<PORT>
# Example for port 8080:
sudo ss -tulnp | grep :8080

Output:

tcp  LISTEN 0 128  *:8080  *:*  users:(("node",pid=1234,fd=12))

Using netstat

sudo netstat -tulnp | grep :<PORT>
# Example for port 8080:
sudo netstat -tulnp | grep :8080

Output:

tcp  0  0 0.0.0.0:8080  0.0.0.0:*  LISTEN  1234/node

Step 2: Terminate the Process

Once you have the PID, use kill to stop it:

Graceful Termination

sudo kill <PID>
# Example:
sudo kill 1234

Forceful Termination (if the process ignores kill)

sudo kill -9 <PID>
# Example:
sudo kill -9 1234

One-Liners to Kill a Process on a Port

Using lsof

sudo kill -9 $(sudo lsof -t -i :<PORT>)
# Example for port 8080:
sudo kill -9 $(sudo lsof -t -i :8080)

Using fuser

sudo fuser -k <PORT>/tcp
# Example for port 8080:
sudo fuser -k 8080/tcp

Using ss with awk

sudo kill -9 $(sudo ss -tulnp | awk '/:<PORT>/ {split($6,a,"="); print a[2]}')
# Example for port 8080:
sudo kill -9 $(sudo ss -tulnp | awk '/:8080/ {split($6,a,"="); print a[2]}')

Examples

Example 1: Kill a Process on Port 3000

sudo kill -9 $(sudo lsof -t -i :3000)

Example 2: Kill a Stubborn Process on Port 5432 (PostgreSQL)

sudo fuser -k 5432/tcp

Key Notes

  1. Permissions: Use sudo to kill processes owned by other users.
  2. Port States:
  • LISTEN: Actively in use.
  • TIME_WAIT: Port temporarily reserved after closing (no action needed; resolves automatically).
  1. Verify Termination:
    Check if the port is free after killing the process:
   sudo lsof -i :<PORT>
   # Or
   nc -zv localhost <PORT>

Troubleshooting

  • No Process Found:
    Ensure the port is in use. Run sudo lsof -i :<PORT> again.
  • “Address Already in Use” After Killing:
    Wait for the OS to release the port (common in TIME_WAIT state) or adjust the kernel parameter net.ipv4.tcp_tw_reuse.

Leave a Reply

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