Find and kill whatever is using a port
For when a service says the address is already in use
Problem: Starting a service fails with "address already in use," and you need to find out what's already listening on that port before you can free it up.
Solution:
lsof -i :9000
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
python3 87 root 3u IPv4 1792818 0t0 TCP *:9000 (LISTEN)
How it works:
-i :9000filterslsof's (list open files) output to sockets on port 9000, on any address.- The
PIDcolumn is what you need next:kill 87stops that specific process. Try a plainkillfirst (sendsSIGTERM, letting the process shut down cleanly) before escalating tokill -9(SIGKILL, immediate and unconditional).SIGTERMgives the process a chance to release a lock or finish a write;SIGKILLdoes not, and processes and signals shows what that costs. lsofis not installed by default on Debian (sudo apt install lsof), which is the reason thessvariation below is worth knowing.
Variations:
# ss: no separate package needed, shows the same information
ss -ltnp 'sport = :9000'
State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
LISTEN 0 5 0.0.0.0:9000 0.0.0.0:* users:(("python3",pid=87,fd=3))
# fuser: identify and kill in one step
fuser -k 9000/tcp
9000/tcp: 87
ss ships with the base system on Debian and doesn't require installing
anything, making it the first thing to try on a box you don't control. fuser -k skips the two-step "find the PID,
then kill it" process entirely, sending SIGTERM straight to whatever's using the port; useful
for a quick cleanup, but skip it when you specifically need to inspect the process (its command
line, working directory, or owner) before deciding whether killing it is the right call.
All three commands default to TCP. A port bound over UDP (common for DNS resolvers or some
monitoring agents) needs -i udp:9000 for lsof, sport = :9000 with -u instead of -t for
ss, or 9000/udp for fuser. If kill doesn't work and the process lingers, kill -9
(SIGKILL) is the next step, bypassing the process's own shutdown handling entirely. If -9
doesn't work either, the process is in an uninterruptible wait on disk or network I/O. Nothing
will move it until that wait ends.
Processes and signals covers how to tell the two cases apart.