Sub topic 10
Freeing space without breaking services
This chapter assumes you can read df and du output, find large files and inode hogs, and recognize a deleted-but-open file with lsof +L1. It also assumes you know what logrotate and the journal do. Here the question is what to do once you know where the space went. A full disk is urgent, and urgency is when people delete the wrong thing.
Principles before commands
Cleanup removes data, and removal is hard to reverse. Four rules keep it safe:
- Identify the owner before you delete. Every large file belongs to a service, a package, or a person. Find out which one.
- Prefer the owner's own cleanup tool. Package managers,
journalctl,docker, and logrotate know which files are safe to remove. A barermdoes not. - Truncate, don't delete, files a process holds open. Deleting an open file frees nothing and hides the file from
du. - Measure after each step. Run
df -hon the affected mount before and after, so you know which action helped.
A safe order of operations
Start with actions that are cheap, reversible, and handled by the owning tool. Move to manual deletion only if those are not enough.
Step 1: Release deleted-but-open files
If df reports far more use than du, a process is probably holding a deleted file. List such files:
sudo lsof -nP +L1The output shows the process name, PID, and the file size. You have two options.
Restart or reload the service. This is the cleanest option, because the process closes the file and the kernel frees the space. Prefer a reload if the service supports it and reopens its logs on SIGHUP or similar.
sudo systemctl reload nginxTruncate through /proc. If you cannot restart the process, you can empty the file through the process's file descriptor. The lsof output includes the PID and the descriptor number (the FD column, for example 4w). Replace 1234 and 4 below with your values:
sudo truncate -s 0 /proc/1234/fd/4This frees the blocks at once. The process keeps writing, so check that it does not refill the space. Fix the underlying cause, usually a log that was removed by hand instead of rotated.
Step 2: Use the owner's cleanup tools
Each of these removes only what its owner considers safe.
Package caches
Downloaded package files are safe to remove because they can be fetched again.
# Debian and Ubuntu
sudo apt-get clean
sudo apt-get autoremove --purge
# RHEL, Rocky, Alma, Fedora
sudo dnf clean allRead the list that autoremove prints before you confirm it. It removes packages nothing depends on, and it should not surprise you.
Old kernels are another common source of space use on /boot. Let the package manager remove them (autoremove does this on Debian and Ubuntu). Do not delete files in /boot by hand, and never remove the kernel you are currently running (check with uname -r).
The systemd journal
The journal can be shrunk without touching other logs:
journalctl --disk-usage
sudo journalctl --vacuum-size=500M--vacuum-size deletes the oldest archived journal files until the total is near the limit. It does not remove the active file. You can also vacuum by age, for example sudo journalctl --vacuum-time=14d. To make a limit permanent, set SystemMaxUse=500M in /etc/systemd/journald.conf, then run sudo systemctl restart systemd-journald.
Containers
If the host runs Docker, images, stopped containers, and build cache can take tens of gigabytes. See what is using space first:
sudo docker system dfThen remove unused objects:
sudo docker system pruneBy default this removes stopped containers, unused networks, dangling images, and dangling build cache. It does not remove volumes. Avoid --volumes unless you have confirmed that no volume holds data you need, because volumes often hold databases.
Step 3: Deal with application logs
Logs are the most common cause of a full disk and the most tempting target for rm. Handle them in this order.
- Check that logrotate covers the log. Look in
/etc/logrotate.d/for a stanza naming the file. If none exists, add one, or the problem will return. - Force a rotation.
sudo logrotate -f /etc/logrotate.d/nginxrotates now and compresses old files if the config asks for it. Test a new config first withsudo logrotate -d /etc/logrotate.conf, which prints what would happen without doing it. - Compress old rotated logs that are still needed:
sudo gzip /var/log/app/app.log.1. - Truncate a live log that is huge and no longer needed:
sudo truncate -s 0 /var/log/app/app.logTruncating keeps the same inode, so a process with the file open continues writing at its current offset. If the program did not open the file in append mode, the file can become sparse: it keeps its old apparent size but uses little real space. Most services open logs in append mode, and that is the usual case. Compare ls -lh with du -h if the numbers look odd.
A minimal rotation stanza for an application log looks like this:
sudo tee /etc/logrotate.d/myapp >/dev/null <<'EOF'
/var/log/myapp/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
copytruncate
}
EOF
sudo logrotate -d /etc/logrotate.d/myappcopytruncate copies the log and then truncates the original. Use it only for programs that cannot reopen their logs. A few lines written between the copy and the truncate can be lost. Programs that reopen on a signal should use a postrotate script that sends that signal instead.
Step 4: Delete files deliberately
If tool-managed cleanup is not enough, you may need to remove files yourself. Follow this routine:
- Name the file or directory and confirm what owns it:
ls -l,dpkg -S /pathorrpm -qf /path, andsystemctl statusfor the likely service. - Check whether anything uses it:
sudo lsof /path/to/fileorsudo fuser -v /path/to/file. - If you are unsure, move it instead of deleting it. Moving within the same filesystem frees nothing, so move it to another filesystem that has room, or compress it where it is.
- Delete with explicit paths, not wildcards you have not previewed. Run
lswith the same glob first.
Inode-heavy directories
When the problem is inodes, a few huge files do not help. You need to remove many small ones. Plain rm -rf on a directory with millions of entries works, but rm * can fail with "Argument list too long". Use find, which streams entries:
sudo find /var/spool/app-cache -xdev -type f -mtime +30 -deleteRun the same command with -print instead of -delete first and read the list. Restricting by age (-mtime +30) lets you remove old files without disturbing files a service is writing now. The -xdev flag keeps find from crossing into other mounts.
Things not to delete
| Path | Why it is dangerous |
|---|---|
| `/var/lib/mysql`, `/var/lib/postgresql` | Live database files. Deleting them corrupts or destroys the database. Use the database's own tools. |
| `/var/lib/docker` contents | Managed by Docker. Use `docker prune` commands. |
| `/boot` kernel files | The system may fail to boot. Use the package manager. |
| `/proc`, `/sys`, `/dev` | Virtual. They use no disk space. |
| Files under `/var/run` or `/run` | Sockets and PID files for running services. |
| `lost+found` | Used by `fsck` for recovered data. Leave it. |
Step 5: When cleanup is not enough
If usage returns within days, deletion is not the fix. Options include:
- Move a large, growing data set (backups, uploads, a database) to a separate volume.
- Enlarge the volume and filesystem. This is covered in later chapters on capacity planning.
- Reduce the reserved-block percentage on a data-only ext4 volume with
tune2fs -m. Do this only on non-root data volumes, and know that it lowers the safety margin that keeps root-owned processes working when the disk fills. - Reduce retention. Shorter log and backup retention is a policy decision, so agree it with the data owner.
Verify the result
After each action, confirm the effect and the health of the service:
df -h /var
df -i /var
systemctl --failed
sudo journalctl -p err -n 20 --no-pagerCheck that df shows the new free space, that no unit has failed, and that recent error messages do not mention disk, space, or missing files. Write down what filled the disk and what you removed. That note decides which monitoring or retention change you make next.
Exercise
df -h /var shows 98% use, but sudo du -xh --max-depth=1 /var adds up to about 40% of the filesystem. A web server writes logs under /var/log/nginx, and an administrator recently ran rm /var/log/nginx/access.log to "clear space". Describe the steps you would take to free the space safely, and explain why the first rm did not help.
Show answer
The rm removed the directory entry, but nginx still has the file open, so the kernel keeps the blocks allocated until the last descriptor closes. du cannot see the file because it has no name, while df counts the blocks. Run sudo lsof -nP +L1 to confirm that an nginx process holds a deleted access.log. Then run sudo systemctl reload nginx so nginx reopens its logs and releases the old file. If a reload is not possible, run sudo truncate -s 0 /proc/PID/fd/N with the PID and descriptor from lsof. Check with df -h /var, and make sure /etc/logrotate.d/nginx exists so the logs are rotated in future instead of removed by hand.
Exercise
df -i /var shows 100% inode use, but df -h /var shows 30% space use. A directory /var/spool/app-cache holds millions of small files, and files older than 30 days are not needed. Write the command you would run first to preview the deletion, and the command to perform it. Explain why you would not use rm /var/spool/app-cache/*.
Show answer
Preview: sudo find /var/spool/app-cache -xdev -type f -mtime +30 -print. Delete: sudo find /var/spool/app-cache -xdev -type f -mtime +30 -delete. The shell would expand * into millions of arguments, which fails with "Argument list too long". It would also delete recent files that the application is still using, and it would not restrict the deletion to regular files older than 30 days. find streams entries and applies the age filter.