0
0
Linux-cliDebug / FixBeginner · 4 min read

How to Fix 'Port Already in Use' Error on Linux

The 'port already in use' error on Linux happens when another process is using the same port. To fix it, find the process using the port with lsof -i :PORT or ss -tulpn | grep PORT, then stop or kill that process to free the port.
🔍

Why This Happens

This error occurs because only one process can listen on a specific network port at a time. If you try to start a server or service on a port already taken by another program, Linux will block it and show the error.

bash
python3 -m http.server 8080
# In another terminal, run the same command again:
python3 -m http.server 8080
Output
OSError: [Errno 98] Address already in use
🔧

The Fix

First, find which process is using the port. Use lsof -i :8080 or ss -tulpn | grep 8080. Then stop or kill that process to free the port. After that, you can start your server without errors.

bash
# Find process using port 8080
lsof -i :8080

# Example output:
# COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
# python3 12345 user    3u  IPv4  123456      0t0  TCP *:http-alt (LISTEN)

# Kill the process
kill 12345

# Start server again
python3 -m http.server 8080
Output
# After kill, no error when starting server Serving HTTP on :: port 8080 (http://[::]:8080/) ...
🛡️

Prevention

Always check if a port is free before starting a service. Use scripts to automate port checks. Avoid hardcoding ports; use configuration files or environment variables to change ports easily. Restart services cleanly to release ports properly.

⚠️

Related Errors

Other common errors include 'Permission denied' when trying to use ports below 1024 without root rights, and 'Connection refused' when no service listens on the target port. Fix these by running with proper permissions or ensuring the service is running.

Key Takeaways

Use lsof -i :PORT or ss -tulpn | grep PORT to find processes using a port.
Kill or stop the process holding the port to free it for your service.
Avoid hardcoding ports; use configuration to change ports easily.
Check port availability before starting services to prevent conflicts.
Understand related errors like permission issues on low ports.