Why Deleting Logs Doesn't Free Linux Disk Space: Complete Troubleshooting Guide
This comprehensive guide explains why deleted log files may not release disk space on Linux, covering file handle leaks, inode exhaustion, sparse files, hard links, mount point issues, filesystem snapshots, and provides step-by-step troubleshooting with commands for logs, Docker, databases, and prevention strategies.
Reading font
Problem Background
Production disk alert shows 99% usage. After deleting large log files in /var/log with rm, df -h still shows 99%. This common ops scenario occurs because file handles aren't released, inodes are exhausted, or the wrong files were deleted.
Core Concepts
File Deletion and File Handles
Linux file deletion has two steps: remove directory entry (dentry), then release inode and data blocks only when inode reference count reaches zero. If a process holds a file descriptor (fd), rm removes the name but inode and blocks persist until the process closes the fd or exits. ls won't show the file, but df shows space still used. Use lsof or /proc/<pid>/fd/ to find processes holding deleted files.
df vs du Difference
df: reads filesystem superblock, shows overall usage including deleted but unreleased files du: traverses directory tree, sums visible files only, excludes deleted files still held by processes
When df shows full but du totals don't match, it's often deleted files with open handles.
Inode Exhaustion
Filesystems allocate fixed inodes at creation. Each file/directory consumes one inode. Small-file scenarios (caches, temp files, mail queues) can exhaust inodes while disk space remains. Check with df -i.
Sparse Files
Sparse files contain "holes" not using actual disk space, but ls -lh shows large apparent size. Compare du -h (actual usage) vs ls -lh (apparent size) to identify. Common in VM images, database files, BitTorrent.
Hard Links
Multiple filenames point to same inode. Deleting one name only decrements link count; space freed only when count reaches zero. Check with ls -li for inode number and link count.
Mount Point Overlay
Files written to a directory before mounting a filesystem there become hidden but still consume space. Unmount to reveal and clean them.
Filesystem Snapshots
LVM, Btrfs, ZFS snapshots consume space not visible in directory tree. Check with lvs, btrfs subvolume list, zfs list -t snapshot.
Overall Troubleshooting Flow
Confirm disk usage: df -h and df -i Compare df and du difference
Find large files: find or du sorting
Check deleted but unreleased files: lsof or /proc/*/fd/ Check inode usage: df -i Check mount points and hidden files
Check filesystem snapshots
Check sparse files and hard links
Clean or release space
Verify space release
Practical Steps
Step 1: Confirm Disk Usage
df -hExample output shows /dev/sda1 at 96% (50G/48G). Then df -i for inodes; example shows /dev/sda1 at 98% inode usage.
Step 2: Find Large Files
du -h --max-depth=1 / 2>/dev/null | sort -hr | head -n 20Drill down: du -h --max-depth=1 /var, then /var/log. Find files >1GB: find /var/log -type f -size +1G -exec ls -lh {} \;. Filter by age:
find /var/log -type f -size +100M -mtime +7 -exec ls -lh {} \;.
Step 3: Compare df and du
df -h /
du -sh /*If df shows 48GB used but du sums to 35GB, ~13GB is held by deleted-but-open files.
Step 4: Check Deleted but Unreleased Files
lsof | grep deletedExample output:
java 12345 appuser 10w REG 253,0 5368709120 131075 /var/log/app.log (deleted)
mysqld 23456 mysql 15w REG 253,0 8589934592 262145 /var/lib/mysql/slow.log (deleted)Column 7 is size in bytes. Filter large deleted files: lsof | grep deleted | awk '$7 > 1073741824 {print $0}'.
Step 5: Handle Deleted but Unreleased Files
Method 1: Restart Process (Recommended)
systemctl restart java-app
systemctl restart mysqlVerify before restart: process state, health checks, maintenance window, stakeholder notification.
Method 2: Truncate File Descriptor (No Restart)
echo "" > /proc/12345/fd/10Immediately frees space. Verify with df -h and lsof -p 12345 | grep deleted. Caveats: loses file content; only for logs/temp files; not for database data or configs; fd persists until process closes it.
Step 6: Check Inode Exhaustion
If df -i shows near 100%, find directories with many small files:
for dir in /*; do echo -n "$dir: "; find "$dir" -xdev -type f 2>/dev/null | wc -l; doneDrill down: for dir in /var/*; do ... done. Inspect file types: ls -lh /var/spool/postfix/maildrop | head -n 20. Clean caches/temp/mail queues: find /var/spool/postfix/maildrop -type f -mtime +7 -delete. High-risk warnings: confirm purpose, backup first, test small scope.
Step 7: Check Mount Point Overlay
If df -h /data shows 95GB used but du -sh /data shows 10GB, files may be hidden under mount. Verify: lsof /data, fuser -m /data, then umount /data. After unmount, check ls -lh /data and du -sh /data. Delete or move hidden files, then remount.
Step 8: Check Filesystem Snapshots
LVM: lvs shows snapshot snap1 with Data% 15.23. Remove: lvremove /dev/vg0/snap1. Check VG space with vgs. Btrfs: btrfs subvolume list /, delete with btrfs subvolume delete /path/to/subvolume. ZFS: zfs list -t snapshot, zfs destroy pool/fs@snapshot.
Step 9: Check Sparse Files
find /var -type f -size +1G -exec du -h {} \; -exec ls -lh {} \; | paste - -If ls shows 10GB but du shows 100MB, it's sparse. Delete if unneeded: rm /var/lib/libvirt/images/vm.img. Compress with cp --sparse=always.
Step 10: Check Hard Links
find /var/log -type f -links +1 -exec ls -li {} \;Link count >1 indicates hard links. Find all names: find / -inum <inode-number> 2>/dev/null. Delete all links to free space.
Step 11: Clean Logs
System Logs
Managed by rsyslog or systemd-journald. Check size: du -sh /var/log, du -sh /var/log/journal. Clean journald: journalctl --vacuum-time=7d, journalctl --vacuum-size=1G. Check logrotate: cat /etc/logrotate.conf, ls -lh /etc/logrotate.d/. Force rotate: logrotate -f /etc/logrotate.conf. Truncate active logs: > /var/log/messages or truncate -s 0 /var/log/messages.
Application Logs
Find:
find /var/log -type f -name "*.log" -size +1G -exec ls -lh {} \;or
find /opt/app -type f -name "*.log" -size +1G -exec ls -lh {} \;. Clean: delete, compress/archive, or truncate if still writing. Example:
find /var/log/app -type f -name "*.log" -mtime +7 -exec gzip {} \;,
find /var/log/app -type f -name "*.log.gz" -mtime +30 -delete.
Web Server Logs
Nginx/Apache access logs grow fast. Check: du -sh /var/log/nginx. Logrotate config: cat /etc/logrotate.d/nginx. Typical config: daily, rotate 7, compress, delaycompress, sharedscripts, postrotate with kill -USR1. Force rotate: logrotate -f /etc/logrotate.d/nginx. Adjust to hourly if needed. Reduce logging: access_log off; in Nginx config, then nginx -t && nginx -s reload.
Step 12: Clean Docker
Check usage: docker system df. Example output shows Images 15.5GB (8.2GB reclaimable), Containers 1.2GB, Volumes 20GB, Build Cache 5GB. Clean: docker image prune -a (unused images), docker container prune (stopped containers), docker volume prune (unused volumes - high risk, verify first), docker builder prune -a (build cache). Nuclear option: docker system prune -a --volumes (dry-run first). Backup volumes before prune:
docker run --rm -v <volume>:/data -v $(pwd):/backup busybox tar czf /backup/volume-backup.tar.gz /data.
Step 13: Clean Database Logs
MySQL
Binlog, slow log, error log. Check binlog size: du -sh /var/lib/mysql, ls -lh /var/lib/mysql/mysql-bin.*. Config: mysql -e "SHOW VARIABLES LIKE 'expire_logs_days';", mysql -e "SHOW VARIABLES LIKE 'binlog_expire_logs_seconds';". Purge:
mysql -e "PURGE BINARY LOGS BEFORE DATE_SUB(NOW(), INTERVAL 7 DAY);"or PURGE BINARY LOGS TO 'mysql-bin.000100';. Risks: verify replica applied binlogs, keep for recovery, backup first. Slow log: du -sh /var/lib/mysql/slow.log, truncate with > /var/lib/mysql/slow.log or mysql -e "FLUSH SLOW LOGS;".
PostgreSQL
WAL in /var/lib/postgresql/14/main/pg_wal. Auto-managed; if piled up, check archive config and replication lag.
Redis
AOF/RDB in /var/lib/redis/. If AOF large: redis-cli BGREWRITEAOF.
Step 14: Clean System Cache and Temp
Check: du -sh /tmp, du -sh /var/tmp, du -sh /var/cache. Clean /tmp: find /tmp -type f -atime +7 -delete, find /tmp -type d -empty -delete. Clean /var/tmp: find /var/tmp -type f -atime +30 -delete. APT: apt-get clean. YUM: yum clean all. systemd coredump: du -sh /var/lib/systemd/coredump, find /var/lib/systemd/coredump -type f -mtime +7 -delete. Disable: echo "Storage=none" >> /etc/systemd/coredump.conf, systemctl restart systemd-coredump.
Step 15: Extend Filesystem
LVM Extend
Check VG free: vgs, vgdisplay. Extend LV: lvextend -L +10G /dev/vg0/root or lvextend -l +100%FREE /dev/vg0/root. Resize FS: ext4 resize2fs /dev/vg0/root, xfs xfs_growfs /. Verify: df -h /.
Cloud Disk Extend
After console resize, rescan: echo 1 > /sys/class/block/sda/device/rescan. Check partitions: fdisk -l /dev/sda, lsblk. If LVM: pvresize /dev/sda2, vgs, lvextend -l +100%FREE /dev/vg0/root, resize2fs /dev/vg0/root. If direct partition: growpart /dev/sda 1, resize2fs /dev/sda1. Verify: df -h.
Command Reference
Disk Space Check
df -h
df -i
du -sh /var/log
du -h --max-depth=1 /var | sort -hr
find /var -type f -size +1G -exec ls -lh {} \;
find /var/log -type f -size +100M -mtime +7 -exec ls -lh {} \;Process and File Handle Check
lsof | grep deleted
lsof -p <pid>
lsof /var/log/app.log
lsof /data
fuser -m /data
echo "" > /proc/<pid>/fd/<fd>Inode Check
find /var -xdev -type f | wc -l
for dir in /var/*; do echo -n "$dir: "; find "$dir" -xdev -type f 2>/dev/null | wc -l; done
find / -xdev -type d -exec sh -c 'echo -n "{}: "; find "{}" -maxdepth 1 -type f | wc -l' \; | sort -t: -k2 -nr | head -n 20Log Cleanup
> /var/log/app.log
truncate -s 0 /var/log/app.log
journalctl --vacuum-time=7d
journalctl --vacuum-size=1G
logrotate -f /etc/logrotate.conf
find /var/log -type f -name "*.log" -mtime +7 -exec gzip {} \;
find /var/log -type f -name "*.log.gz" -mtime +30 -deleteDocker Cleanup
docker system df
docker image prune -a
docker container prune
docker volume prune
docker builder prune -a
docker system prune -a --volumesMySQL Log Cleanup
mysql -e "SHOW VARIABLES LIKE 'expire_logs_days';"
mysql -e "SHOW VARIABLES LIKE 'binlog_expire_logs_seconds';"
mysql -e "SHOW BINARY LOGS;"
mysql -e "PURGE BINARY LOGS BEFORE DATE_SUB(NOW(), INTERVAL 7 DAY);"
mysql -e "PURGE BINARY LOGS TO 'mysql-bin.000100';"
mysql -e "FLUSH SLOW LOGS;"Filesystem Extend
lvextend -L +10G /dev/vg0/root
lvextend -l +100%FREE /dev/vg0/root
resize2fs /dev/vg0/root # ext4
xfs_growfs / # xfs
echo 1 > /sys/class/block/sda/device/rescan
pvresize /dev/sda2
lvextend -l +100%FREE /dev/vg0/root
resize2fs /dev/vg0/root
growpart /dev/sda 1
resize2fs /dev/sda1Configuration Examples
logrotate Config
/var/log/app/*.log {
daily
rotate 7
missingok
notifempty
compress
delaycompress
sharedscripts
postrotate
/usr/bin/systemctl reload app > /dev/null 2>&1 || true
endscript
maxsize 500M
dateext
dateformat -%Y%m%d-%s
}Options: daily (rotate daily), rotate 7 (keep 7), missingok (no error if missing), notifempty (skip empty), compress (gzip old), delaycompress (compress next rotation), sharedscripts (run once for multiple logs), postrotate (script after rotate), maxsize 500M (rotate if exceeds), dateext/dateformat (date suffix).
journald Config
[Journal]
SystemMaxUse=1G
SystemMaxFileSize=100M
RuntimeMaxUse=100M
MaxRetentionSec=7day
ForwardToSyslog=noSystemMaxUse: max persistent log space. SystemMaxFileSize: max single file. RuntimeMaxUse: max volatile log space. MaxRetentionSec: max retention time. ForwardToSyslog: forward to syslog.
MySQL Binlog Config
[mysqld]
server-id = 1
log_bin = /var/lib/mysql/mysql-bin
binlog_format = ROW
expire_logs_days = 7
max_binlog_size = 1G
slow_query_log = 1
slow_query_log_file = /var/lib/mysql/slow.log
long_query_time = 2
log_queries_not_using_indexes = 0expire_logs_days: binlog retention days (MySQL 5.7). binlog_expire_logs_seconds: retention seconds (MySQL 8.0, higher priority). max_binlog_size: max single binlog file. slow_query_log: enable slow log. long_query_time: threshold in seconds.
Temp Cleanup Script
#!/bin/bash
find /tmp -type f -atime +7 -delete 2>/dev/null
find /var/tmp -type f -atime +30 -delete 2>/dev/null
find /tmp -type d -empty -delete 2>/dev/null
find /var/tmp -type d -empty -delete 2>/dev/null
find /var/lib/systemd/coredump -type f -mtime +7 -delete 2>/dev/null
find /var/log -type f -name "*.gz" -mtime +30 -delete 2>/dev/null
echo "$(date): Cleanup completed" >> /var/log/cleanup-tmp.logMake executable: chmod +x /etc/cron.daily/cleanup-tmp. Test: /etc/cron.daily/cleanup-tmp.
Disk Monitor Script
#!/bin/bash
THRESHOLD=90
df -h | awk 'NR>1 {print $5,$6}' | while read usage mountpoint; do
usage=${usage%\%}
if [ "$usage" -ge "$THRESHOLD" ]; then
echo "$(date): WARNING - $mountpoint is ${usage}% full" | tee -a /var/log/disk-check.log
fi
done
df -i | awk 'NR>1 {print $5,$6}' | while read usage mountpoint; do
usage=${usage%\%}
if [ "$usage" -ge "$THRESHOLD" ]; then
echo "$(date): WARNING - $mountpoint inode is ${usage}% full" | tee -a /var/log/disk-check.log
fi
doneAdd to crontab hourly: echo "0 * * * * /usr/local/bin/check-disk.sh" | crontab -.
Monitoring and Observability
Disk IO Monitoring
iostat -xz 1. Key metrics: %util (near 100% = saturated), await (avg wait time), r/s / w/s (IOPS), rkB/s / wkB/s (throughput).
Disk Space Trend
sar -F 1for history. Or custom:
echo "$(date),$(df -h / | awk 'NR==2 {print $5}')" >> /var/log/disk-usage.csv.
Filesystem Events
inotifywait -m -r -e create,delete,modify /var/logto trace rapid file writes.
Process IO Analysis
iotop -o(only active). pidstat -d 1 for per-process IO details.
Troubleshooting Decision Tree
Disk Space Alert
|-- df -h --> usage > 90%
|-- df -i --> inode high
| |-- find many small files dir
| |-- clean or migrate
|-- du vs df diff large
| |-- lsof | grep deleted
| |-- restart process or truncate fd
|-- du finds large dir
|-- log files
| |-- logrotate
| |-- truncate
| |-- compress/archive
|-- app data
| |-- backup/archive
| |-- clean expired
|-- Docker
| |-- docker system df
| |-- prune
|-- database logs
|-- binlog
|-- slow query log
|-- WAL
|-- cleanup still insufficient
|-- extend filesystem
|-- migrate data
|-- mount new diskRisk Warnings
File Deletion Risks
Confirm file purpose and business impact before delete
Backup production data before deletion
Test batch delete with small scope first
Use find -ls to preview before find -delete Never run rm -rf on root
Avoid wildcard deletes
Process Restart Risks
Confirm process state and business impact
Stateful services (DB, MQ) need impact assessment
Verify health checks and auto-restart
Notify stakeholders before restart
Verify service health after restart
Log Cleanup Risks
Don't rm actively written logs
Confirm no audit/trace impact before clearing
Verify replica status before binlog purge
Confirm slow log not needed for perf analysis
Docker Cleanup Risks
Volumes may contain DB/app data - verify first
Prune is irreversible
Avoid docker system prune -a --volumes in prod
Backup important volumes before cleanup
Filesystem Extend Risks
Backup critical data before extend
Online extend has risk - use maintenance window
Partition extend requires unmount (downtime)
Cloud disk resize needs manual OS recognition
LVM extend is irreversible
Mount Point Operation Risks
Confirm no processes using mount point before unmount
Unmount then delete is irreversible
Verify /etc/fstab before remount
Errors can prevent system boot
Verification Methods
Space Release Verification
df -h
df -iConfirm usage dropped.
Process File Handle Verification
lsof -p <pid> | grep deletedConfirm no deleted files.
Log Cleanup Verification
du -sh /var/log
ls -lh /var/log/app.logConfirm expected sizes.
Docker Cleanup Verification
docker system dfConfirm reclaimable space reduced.
Filesystem Extend Verification
df -h
lsblk
lvsConfirm capacity increased.
Business Function Verification
Access app URL - confirm normal response
Check logs writing normally
Check monitoring metrics normal
Check DB connections normal
Check replication normal
Rollback Plans
File Deletion Rollback
Restore from backup if available
DB files: recover from binlog/WAL
App files: restore from version control
Log files: unrecoverable but non-critical
Prevention: backup before delete, use mv instead of rm with observation period, version control/snapshots for critical files.
Process Restart Rollback
Rollback config to previous version
Rollback code to previous version
Ensure health checks and auto-restart
DB: restore from backup
Config Change Rollback
cp /etc/nginx/nginx.conf.bak /etc/nginx/nginx.conf
nginx -t && systemctl restart nginxOr from git:
cd /etc && git checkout nginx/nginx.conf && systemctl restart nginx.
Filesystem Extend Rollback
Irreversible - must backup before extend.
Production Operation Guidelines
Pre-Operation Checks
Confirm environment: dev/test/prod
Confirm maintenance window, avoid peak
Confirm backup and rollback plan
Confirm monitoring and alerting
Confirm permissions and approval process
During Operation
Log all commands and operations
Execute stepwise, not batch
Verify after each step
Stop on anomalies, investigate
Maintain communication with business
Post-Operation Verification
Verify disk space released
Verify business functions normal
Verify monitoring metrics normal
Verify logs writing normally
Verify DB replication normal
Documentation and Retrospective
Record root cause and resolution
Update runbooks and SOPs
Summarize lessons learned
Improve monitoring and alerting
Implement preventive measures
Preventive Measures
Disk Space Monitoring
Alert at 80% usage, critical at 90%
Inode alert at 80%
Disk IO saturation alert
Tools: Prometheus+Grafana, Zabbix, Nagios, cloud monitoring
Log Management Strategy
All logs under logrotate
Retention per audit requirements
Compress and archive to object storage
Disable unnecessary debug logs
Check disk space before log writes
Application Design
Log to stdout for container runtime management
Periodic temp file cleanup
Cache files with TTL
Chunk large file uploads/storage
Data archival strategy
Capacity Planning
Regular capacity trend analysis
Proactive expansion with buffer
Forecast based on business growth
Migrate cold data to low-cost storage
Automated Cleanup
Scheduled temp file cleanup
Scheduled old log cleanup
Scheduled Docker unused resource cleanup
Scheduled DB log cleanup
Automation scripts with result logging
Summary
Core troubleshooting logic: df and df -i to distinguish space vs inode full du to find large directories/files
Compare df vs du for deleted-but-open files lsof | grep deleted to find holding processes
Restart process or truncate fd to release
Check logs, Docker, DB logs as common culprits
Clean or archive unneeded files
If still insufficient, extend FS or migrate data
Establish monitoring, alerting, and automation for prevention
Production operation principles: confirm impact before delete, verify health checks and rollback before restart, test batch operations small-scale first, backup before high-risk actions, verify business and monitoring after changes, document everything for continuous improvement. Most importantly: don't just delete files to free space - find root cause and build long-term solutions.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.
Published
AI-assisted summary