lsof, ss and ncdu
Which process holds a file open, which service listens on which port, and what fills the disk: three small tools for daily troubleshooting.
lsof: who has this open?
Remember everything is a file: open files, folders, sockets and devices. lsof (“list open files”) shows which process uses which of them. Run it with sudo to see all processes.
| What | Command |
|---|---|
| Who uses this file? | sudo lsof /var/log/syslog |
| Who uses something below this folder / mount? (“target is busy”) | sudo lsof +D /data (or sudo lsof /data for the mount point) |
| What does this process have open? | sudo lsof -p 1234 |
| Everything a user has open | sudo lsof -u anna |
| Everything a program has open | sudo lsof -c nginx |
| Who uses port 443? | sudo lsof -i :443 |
| All network connections | sudo lsof -i -P -n |
| Deleted files still taking space | sudo lsof +L1 |
-P -n show port numbers and IPs instead of names (faster).
Disk full, but du finds nothing? A process still holds a deleted file open, so the space isn’t freed. sudo lsof +L1 shows it; restart that service (often a log file deleted by hand instead of rotated).
ss: ports and connections
ss replaces the old netstat (not installed by default).
| What | Command |
|---|---|
| Listening ports with process | sudo ss -tulpn |
| Only TCP / only UDP listeners | sudo ss -tlpn / sudo ss -ulpn |
| Who listens on port 80? | sudo ss -tlpn 'sport = :80' |
| All established TCP connections | ss -tn state established |
| Connections to a remote port | ss -tn 'dport = :5432' |
| Connections from one IP | ss -tn 'dst 10.0.0.21' |
| Count connections per state | ss -tan | awk 'NR>1 {print $1}' | sort | uniq -c |
| Summary | ss -s |
The letters: t TCP, u UDP, l listening, p process, n numeric.
Reading the address column:
| Local address | Reachable from |
|---|---|
0.0.0.0:80 / [::]:80 / *:80 | everywhere (all interfaces) |
127.0.0.1:5432 | only this server |
10.0.0.11:8080 | only via that IP |
ncdu: what fills the disk?
du gives numbers; ncdu gives an interactive, sorted browser of the biggest folders.
sudo apt install ncdu
sudo ncdu -x / # -x: stay on this file system (skip /proc, other disks)
| Key | Does |
|---|---|
↑ ↓ / Enter | move / open folder |
← | back up |
d | delete the selected file or folder (asks first) |
g | show percentages / graph |
i | info about the item |
q | quit |
Usual suspects: /var/log, /var/lib/docker, /var/cache/apt, /home, old kernels in /boot, core dumps in /var/crash. What to do about each: Disk full: find and free space.
Without ncdu:
sudo du -xh --max-depth=1 / | sort -h | tail