How to kill the process using a port on Linux
Something is already listening on the port your server needs. On Linux you can find the process with ss or lsof and stop it with kill. The examples use port 3000.
Quick answer
The users: column shows the program name and its PID.
sudo ss -ltnp 'sport = :3000'LISTEN 0 511 *:3000 *:* users:(("node",pid=4242,fd=19))kill 4242With lsof
-t prints only PIDs, which is handy in scripts. -sTCP:LISTEN skips ordinary connections to that port.
sudo lsof -nP -iTCP:3000 -sTCP:LISTENkill $(sudo lsof -t -iTCP:3000 -sTCP:LISTEN)With fuser
Without -TERM, fuser -k sends SIGKILL, which gives the program no chance to clean up.
sudo fuser -k -TERM 3000/tcpkill or kill -9?
kill <PID>sends SIGTERM: the program can close connections and save state. Try this first.kill -9 <PID>(SIGKILL) ends it immediately. Use it only if the process is still there after a few seconds.
Why sudo?
Without root, ss and lsof can't see other users' processes: the port shows up, but the process column is empty. Services such as PostgreSQL and Docker run as other users, so use sudo to see and stop them.
It comes straight back
Something is restarting it. Find out what owns the process:
- A systemd service:
systemctl status 4242names the unit. Stop it withsudo systemctl stop <unit>, andsudo systemctl disable <unit>to keep it from starting at boot. - A Docker container: the port is held by
docker-proxy. Rundocker ps --filter "publish=3000"and stop the container (see Docker port already allocated). - A process manager or file watcher (pm2, nodemon, supervisord): stop it there, for example
pm2 stop <name>.
See what you are killing first, with portfind
portfind lists every listening port with the process, its project folder, uptime, risk level and Docker container. Type the port, press Enter: it sends SIGTERM, then SIGKILL after 5 seconds if needed. If you kill the same port three times in 15 minutes, it tells you something keeps restarting it.
curl -fsSL https://raw.githubusercontent.com/rpratap2111/portfind/main/install.sh | shportfind