Sub topic 2
Drilling down with du
This chapter assumes you can work in a Linux shell over SSH, run commands with sudo, and combine commands with pipes. du (disk usage) reports how much space each file and directory uses. When df shows a filesystem is nearly full, du tells you where the space went.
Drilling down with du
Start at the top of the affected filesystem and work down one level at a time:
sudo du -xh --max-depth=1 /var 2>/dev/null | sort -h | tail -n 10The -x option keeps du on one filesystem, so it does not count mounted volumes. --max-depth=1 prints only the direct children of /var. sort -h orders the sizes by human-readable value, and tail keeps the largest ten. Pick the largest directory, then repeat the command on it until you reach the files.
Finding large files and directories with millions of files
Large files are easy to find with find:
sudo find / -xdev -type f -size +500M -exec ls -lh {} + 2>/dev/nullDirectories with millions of small files are harder. They use little space but consume inodes, the per-file records a filesystem has a fixed number of. Count the entries under each directory in /var:
for d in /var/*; do
printf '%s %s\n' "$(sudo find "$d" -xdev 2>/dev/null | wc -l)" "$d"
done | sort -n | tail -n 5This scan can take several minutes on a busy server, so run it during a quiet period.
Why inodes run out: mail queues, session files, caches
Inode exhaustion usually comes from software that creates many small files and never removes them. Common sources include:
- Mail queues, such as
/var/spool/postfix, when delivery fails for a long time. - PHP session files, such as
/var/lib/php/sessions, when garbage collection is off. - Application caches that write one file per item and have no expiry.
Fix the cause first. Deleting files without stopping the writer only delays the problem.
When df and du disagree: deleted files still held open
Sometimes df reports a filesystem as full, but du on the same filesystem adds up to much less. A process may hold open a file that was deleted. The space is not freed until the process closes the file. List these files:
sudo lsof -nP +L1The +L1 option shows open files with a link count below one, which means they were deleted.
> Warning: Restart only services you understand, and only during an acceptable window. Do not delete /proc entries or kill processes you cannot identify.
Exercise
On a server, df -h / shows 95% used, but sudo du -xh --max-depth=1 / | sort -h | tail adds up to about 40% of the disk. What is the most likely cause, and which command would confirm it?
Show answer
The most likely cause is deleted files that a running process still holds open. Run sudo lsof -nP +L1 to list them. The output shows the process ID and the size of each deleted file, which identifies the process to restart.