Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Operations 41 min read

Ghost Files: Why Deleting 200GB Logs Didn't Free Disk Space

This guide explains why disk space isn't freed after deleting large log files due to 'ghost files' (deleted but still open by processes), and provides step-by-step Linux commands to identify the holding processes, verify inode usage, safely release space via application reload or truncation, and prevent recurrence with proper log rotation.

Introduction

One of the most confusing disk alerts during on-call duty: du shows the directory has shrunk, but df still reports the filesystem near 100%. The log files were removed with rm, so why didn't the space return?

In Linux, a directory entry is merely a reference from a filename to an inode. After a process opens a file, the kernel's open file object continues to point to that inode. rm removes the directory entry and decrements the link count; as long as any process holds that inode, its data blocks cannot be reclaimed. The file has no pathname and is often called a "deleted but still open file" or "ghost file." This is not a filesystem error—it's the Unix file semantics guarantee that a process's existing file descriptors remain valid even if another process deletes the file.

However, df vs du mismatch has other causes: mount points covering lower directories, ext4 reserved blocks, container overlay filesystems, snapshots, sparse files, hard links, and filesystem metadata. Troubleshooting must first confirm the object, then release space—never restart the whole machine just because you see (deleted).

Stop Growth First, Preserve the Scene

When the disk is near full, the most dangerous action is to keep running scans, compressions, or copies that generate massive output. First verify which mount point the alert targets, how many blocks and inodes remain, and whether the log write rate is still climbing.

date --iso-8601=seconds
 df -hT
 df -ih
 findmnt -o TARGET,SOURCE,FSTYPE,OPTIONS
 sudo du -xhd1 /var 2>/dev/null | sort -h
 sudo du -xhd1 /var/log 2>/dev/null | sort -h
 sudo find /var/log -xdev -type f -size +1G -printf '%s %p
' 2>/dev/null |
 sort -nr | numfmt --field=1 --to=iec | head -n 30
df -hT

checks data blocks; df -i checks inodes. Inode exhaustion prevents file creation even if capacity remains—two completely different failure modes. findmnt confirms whether /var/log is a separate mount, LVM, network disk, or container storage, avoiding operations on the wrong device. The last three commands stay within the target filesystem; -x prevents crossing mount points. If the root partition is full, don't redirect error output to a local file.

Do not delete unknown files at this stage. Instead, lower non-critical log levels, temporarily drain traffic from the faulty node, or pause the batch job causing the flood. Pausing affects business and must be approved by the service owner; never stop database, audit, or security logs just to save disk space.

For systemd journal, first inspect usage and time range read-only:

journalctl --disk-usage
 journalctl --list-boots
 journalctl --since '-30 min' -p warning --no-pager | tail -n 100
 journalctl --since '-15 min' -o json --no-pager |
 jq -r '._SYSTEMD_UNIT // .SYSLOG_IDENTIFIER // "unknown"' |
 sort | uniq -c | sort -nr | head -n 20

If it's a log flood, locate the source unit first, not vacuum. The last command roughly sorts by journal line count in the last 15 minutes; one line ≠ one byte, but it quickly reveals anomalous services.

Form a Hypothesis from the df/du Gap

df

queries the filesystem for used blocks; du traverses visible directory entries and sums file usage. If df is significantly larger than du on the same mount point, some used blocks are no longer reachable via the current directory tree. Deleted-but-open files are the prime suspect.

The script below calculates the approximate gap on a single mount point. Running du can add read pressure on busy storage; in production peaks, limit priority and scan only the target mount.

#!/usr/bin/env bash
 set -euo pipefail

 mountpoint=${1:-/var}
 df_used=$(df -B1 --output=used "$mountpoint" | awk 'NR==2{print $1}')
 du_used=$(nice -n 19 ionice -c3 du -x -s -B1 "$mountpoint" 2>/dev/null | awk '{print $1}')
 gap=$((df_used-du_used))
 printf 'mount=%s df_used=%s du_visible=%s gap=%s
' \
   "$mountpoint" "$df_used" "$du_used" "$gap"
 numfmt --to=iec "$df_used" "$du_used" "$gap"

The gap is not a strict equality: df includes filesystem metadata and reserved space; du behaves differently with hard links, sparse files, permission failures, and concurrent changes. Only when the gap reaches tens or hundreds of GB and a corresponding deleted FD exists is the evidence chain complete.

Simultaneously confirm whether the alert reads the host or container filesystem. Use readlink /proc/1/ns/mnt to get the host mount namespace identifier, then readlink /proc/PID/ns/mnt for the target process; different targets mean different mount namespaces. Finally, findmnt -T /var/log confirms which mount the path resides on.

Directly Find Deleted-but-Open Files

When lsof is installed, +L1 selects files with link count less than 1—i.e., directory entry deleted but still held open by a process. -nP avoids DNS and service name resolution, making incident queries faster and more deterministic.

sudo lsof -nP +L1
 sudo lsof -nP +L1 -F pcfnst 2>/dev/null |
 awk '
  /^p/{pid=substr($0,2)} /^c/{cmd=substr($0,2)} /^f/{fd=substr($0,2)}
  /^s/{size=substr($0,2)} /^n/{name=substr($0,2); if(size+0>0) print size,pid,cmd,fd,name}
 ' | sort -nr | head -n 30 | numfmt --field=1 --to=iec

The first command is good for quick browsing; output fields COMMAND, PID, FD, TYPE, SIZE/OFF, and NAME are most critical. FD may show 4w (opened for write); NAME usually ends with (deleted). The second command uses field mode to sort by size, avoiding manual search for the largest objects. lsof fields may be missing across versions and file types; the script treats size as an approximate filter. For regular log files this is usually sufficient; do not interpret socket, pipe, or memory-mapped SIZE/OFF as releasable disk space.

Without lsof, you can find symlinks from /proc. This traverses process FDs; on nodes with many containers and processes it has cost but does not modify the system.

sudo find /proc/[0-9]*/fd -lname '* (deleted)' -printf '%p -> %l
' 2>/dev/null

To get actual block usage, don't trust logical file size alone. stat 's %s is logical bytes; %b × 512 is allocated block bytes; sparse files can differ greatly.

pid=1234
 fd=7
 sudo stat -Lc 'path=%n size=%s blocks=%b block_unit=%B inode=%i links=%h' "/proc/$pid/fd/$fd"
 sudo readlink "/proc/$pid/fd/$fd"
stat -L

follows the FD link, accessing the inode even if the original path is deleted. The example PID/FD must be replaced with live values; after the process exits or the FD is reused the path becomes invalid, so re-verify inode, process start time, and service ownership before acting.

The full inspection script below uses /proc to output regular deleted FDs: PID, FD, allocated bytes, logical bytes, command, and target. It does not read file content.

#!/usr/bin/env bash
 set -u

 printf '%-8s %-8s %-14s %-14s %-20s %s
' PID FD ALLOCATED LOGICAL COMMAND TARGET
 for link in /proc/[0-9]*/fd/*; do
   target=$(readlink "$link" 2>/dev/null) || continue
   [[ $target == *' (deleted)' ]] || continue
   pid=${link#/proc/}; pid=${pid%%/*}; fd=${link##*/}
   type=$(stat -Lc '%F' "$link" 2>/dev/null) || continue
   [[ $type == 'regular file' ]] || continue
   read -r logical blocks block_size <<(stat -Lc '%s %b %B' "$link")
   allocated=$((blocks*block_size))
   command=$(tr -d '
' < "/proc/$pid/comm" 2>/dev/null)
   printf '%-8s %-8s %-14s %-14s %-20s %s
' \
     "$pid" "$fd" "$allocated" "$logical" "$command" "$target"
 done | sort -k3,3nr

If the script doesn't run as root, hidepid, Yama, or container permissions may cause false negatives—absence of output doesn't prove no ghost files exist. Also, the same open file may be shared by multiple FDs or forked processes; simple addition double-counts. Final verification uses inode, device number, and df change.

pid=1234
 fd=7
 sudo stat -Lc 'device=%d inode=%i links=%h bytes=%s blocks=%b' "/proc/$pid/fd/$fd"
 sudo ls -l "/proc/$pid/fd/$fd"
 ps -p "$pid" -o pid,ppid,lstart,etime,user,cmd

Why the Process Keeps Writing After Log Deletion

The typical chain: application starts with open("app.log", O_APPEND), obtaining FD 7; rotation script does mv or rm; the application receives no reopen signal and does not reopen based on inode change; subsequent write(7, ...) calls continue writing to the old inode. The newly created same-named app.log in the directory is a completely different file.

Comparing the inodes of the path and the FD proves this.

pid=1234
 fd=7
 sudo stat -Lc 'fd inode=%i device=%d size=%s links=%h' "/proc/$pid/fd/$fd"
 sudo stat -Lc 'path inode=%i device=%d size=%s links=%h' /var/log/myapp/app.log

The FD shows links=0 and a different inode—that's deletion with continued writes. If inodes match, it may be an lsof display race or the current path is still one of the hard links. strace can confirm whether the process still writes to that FD, but attaching has performance and compliance impact. A controlled sample:

sudo timeout 10 strace -f -p 1234 -e trace=write,writev,openat,close -s 80 -tt -T -o /var/tmp/myapp-io.strace

The PID must come from the earlier verification; 10-second timeout limits attach time; never run on sensitive services without approval. The trace file may contain log fragments—treat as production data and clean up promptly. eBPF tools can reduce overhead in some scenarios but still require kernel support and access control verification.

Choose Release Method: Prefer Application Reopen

The safest fix uses the application's supported reopen/reload mechanism, letting the process close the old FD and open a new file. The exact signal cannot be guessed: Nginx uses USR1 for reopen, some daemons use HUP, Java applications often rely on Logback/Log4j2 rotation. Check the installed version's documentation and unit configuration first.

Nginx example: verify config and PID, send USR1, then check old/new inodes and error log. This should not interrupt connections, but wrong PID or permissions can cause reopen failure.

sudo nginx -t
 pid=$(cat /run/nginx.pid)
 ps -p "$pid" -o pid,lstart,cmd
 sudo kill -USR1 "$pid"
 sleep 2
 sudo lsof -nP +L1 -a -p "$pid"
 sudo tail -n 50 /var/log/nginx/error.log

For systemd-managed services supporting reload, first inspect the unit definition to confirm what ExecReload does.

systemctl show myapp.service -p MainPID -p ExecReload -p CanReload
 systemctl cat myapp.service
 sudo systemctl reload myapp.service
 systemctl is-active myapp.service

If the application only opens logs at startup, a graceful restart may be needed. Restart affects connections and memory state; drain traffic first, confirm other healthy replicas, save config and runtime parameters, and set up rollback. The flow below illustrates a single node after load-balancer removal; actual drain commands are platform-specific.

service=myapp.service
 systemctl is-active "$service"
 systemctl show "$service" -p MainPID -p ActiveEnterTimestamp
 sudo systemctl restart "$service"
 systemctl is-active "$service"
 journalctl -u "$service" --since '-2 min' --no-pager | tail -n 100
 curl -fsS --max-time 3 http://127.0.0.1:8080/healthz

If startup fails, keep the node drained, roll back to the previously verified config/binary, and restart again. Don't restart all replicas just because of disk pressure. After release, confirm df, not just service active status.

df -hT /var/log
 sudo lsof -nP +L1 | head -n 50
 ss -lntp | grep ':8080 '

Emergency Measure: Truncate via /proc/PID/fd/N

When space has only minutes left, the service cannot restart immediately, and the application lacks a reopen mechanism, you can truncate the deleted FD to zero. This permanently loses log content and may interact with the application's current offset—only as an approved emergency measure.

Before execution, re-verify: target is a regular file; link still shows (deleted); PID belongs to the correct service; device and inode match previous step; whether data needs forensic preservation; whether enough space exists to copy. Never do this on database data files, WAL, unknown files in container writable layers, or mmap'd files.

If another filesystem has space, save the content first via the FD:

pid=1234
 fd=7
 dest=/mnt/recovery/myapp.deleted.$(date +%Y%m%d-%H%M%S).log
 sudo stat -Lc '%F device=%d inode=%i links=%h size=%s blocks=%b' "/proc/$pid/fd/$fd"
 sudo cp --sparse=always --reflink=auto "/proc/$pid/fd/$fd" "$dest"
 sudo sync -f "$dest"
 sudo sha256sum "$dest"

The copy captures a changing file; the hash only identifies the replica, not point-in-time consistency. If space is tight, prioritize the business-required time window or let security/audit decide the forensic method.

Then truncate: record df, inode, and size; use truncate with explicit target; no wildcards.

pid=1234
 fd=7
 sudo readlink "/proc/$pid/fd/$fd"
 sudo stat -Lc 'device=%d inode=%i links=%h size=%s blocks=%b' "/proc/$pid/fd/$fd"
 df -B1 /var/log
 sudo truncate -s 0 "/proc/$pid/fd/$fd"
 df -B1 /var/log
 sudo stat -Lc 'device=%d inode=%i links=%h size=%s blocks=%b' "/proc/$pid/fd/$fd"

Truncation is irreversible; the saved copy is only for audit or analysis, cannot restore the original process's lost content. Some non- O_APPEND writers retain the original file offset; after truncation the next write may occur at a high offset, creating a sparse file and causing logical size to jump back. Continue monitoring FD size; root cause fix remains reopen or restart.

watch -n 2 "stat -Lc 'size=%s blocks=%b inode=%i' /proc/1234/fd/7; df -h /var/log"

Shell redirection : > /proc/.../fd/... also truncates, but truncate expresses intent more clearly and is easier to audit. Never rm /proc/PID/fd/N: it's not a regular directory entry, and deleting it does not close the target process's FD.

Don't Miss mmap, Inherited FDs, and Container Processes

Files may be memory-mapped and not appear in regular FD lists, or the FD may be closed while the mapping persists. lsof +L1 usually shows DEL / mem entries; /proc/PID/maps also confirms.

sudo grep -H ' (deleted)$' /proc/[0-9]*/maps 2>/dev/null | head -n 50
 sudo lsof -nP +L1 | awk '$4=="DEL" || $4=="mem" {print}' | head -n 50

Do not truncate unknown mmap files. Databases, JVM, shared libraries, and temporary files may depend on mapped content; prefer the application's supported exit/reload flow.

Log FDs can also be inherited by child processes via fork/exec. Multiple PIDs pointing to the same device and inode mean the last reference must close before space is released.

target_inode=123456
 for link in /proc/[0-9]*/fd/*; do
   inode=$(stat -Lc '%i' "$link" 2>/dev/null) || continue
   [ "$inode" = "$target_inode" ] || continue
   printf '%s %s
' "$link" "$(readlink "$link" 2>/dev/null)"
 done

Inode is unique only within a device; automation should also compare st_dev. Service restart but space not released often means old workers are gracefully exiting, orphaned children still hold FDs, or only a container-internal process was restarted.

Container scenarios: confirm container PID and overlay mount from the host. Commands vary by runtime; for containerd/CRI:

sudo crictl ps --name myapp
 container_id=$(sudo crictl ps --name myapp -q | head -n1)
 sudo crictl inspect "$container_id" | jq '.info.pid, .status.metadata.name'
 host_pid=$(sudo crictl inspect "$container_id" | jq -r '.info.pid')
 sudo nsenter -t "$host_pid" -m -- findmnt -T /var/log/myapp/app.log

Container logs are often written by kubelet or the runtime on the host; the application deleting its own visible path may not affect the host JSON logs. Check /var/log/pods, /var/log/containers, and runtime storage separately; never manually delete overlay2 / containerd metadata directories.

sudo du -xhd2 /var/log/pods 2>/dev/null | sort -h | tail -n 30
 sudo find /var/log/pods -xdev -type f -name '*.log' -size +500M \
   -printf '%s %p
' 2>/dev/null | sort -nr | numfmt --field=1 --to=iec
 sudo lsof -nP +L1 /var/lib/containerd 2>/dev/null | head -n 50

If No Deleted FD, Check Four Other Difference Categories

Mount Point Covering Lower Files

If a directory receives heavy writes and then a new filesystem is mounted on top, du sees only the upper layer while the lower files still consume the root partition. Don't recklessly unmount a production mount. Create a bind mount view of the root filesystem to inspect the lower path.

sudo mkdir -p /mnt/root-view
 root_source=$(findmnt -n -o SOURCE /)
 echo "root source: $root_source"
 sudo mount --bind / /mnt/root-view
 sudo du -xhd2 /mnt/root-view/var 2>/dev/null | sort -h | tail -n 30
 sudo umount /mnt/root-view

A regular bind mount is not recursive; it usually doesn't replicate child mounts, so the new path reveals directories hidden by child mounts. Still verify with findmnt -R /mnt/root-view. Complex shared-mount propagation scenarios should use a separate mount namespace or rescue environment. Risky unmounts, read-only mounts, and lower-layer cleanup must be done in a maintenance window after confirming no processes are using them.

ext4 Reserved Blocks

ext4 defaults to reserving a percentage of blocks for privileged processes; regular users see them as unavailable. Large data partitions can reduce this percentage, but root reserved space helps admins log in and services write critical files. First get the device: device=$(findmnt -n -o SOURCE /var), then read reserved blocks with

sudo tune2fs -l "$device" | grep -E 'Block count|Reserved block count|Block size|Reserved block percentage'

. Only interpret if findmnt confirms it's an ext4 block device.

Changing reserved percentage is a filesystem-level change. Confirm the device is ext4, have a backup, and calculate absolute reserved amount. Example adjusts an independent data volume to 1%—not for root, not for XFS.

device=/dev/mapper/vg_logs-lv_logs
 sudo tune2fs -m 1 "$device"
 sudo tune2fs -l "$device" | grep -E 'Reserved block count|Reserved block percentage'
 df -hT /var/log

Rollback with tune2fs -m <original>, but if the newly freed space has already been filled, restoring a higher reserve will further reduce user-available space.

Hard Links and Sparse Files

Deleting one hard link doesn't release the inode if another path exists. Find all links by inode, restricted to the same filesystem.

file=/var/log/archive/app.log
 inode=$(stat -c '%i' "$file")
 device=$(stat -c '%d' "$file")
 printf 'device=%s inode=%s links=%s
' "$device" "$inode" "$(stat -c '%h' "$file")"
 sudo find /var/log -xdev -inum "$inode" -ls
 ls -lh /var/log/myapp/large.log
 du -h /var/log/myapp/large.log
 stat -c 'logical=%s blocks=%b block_unit=512' /var/log/myapp/large.log

The first five commands find hard links; inode is unique per device, so record device number and limit to the same filesystem. The last three identify sparse files: logical size large, actual blocks small; ls -lh vs du -h difference is normal.

Snapshots, Quotas, and Filesystem Features

LVM thin snapshots, cloud disk snapshots usually don't count directly in the mount's df, but the storage pool may exhaust due to COW growth. XFS project quota, btrfs subvol/qgroup, Ceph have their own accounting. Identify the technology first, then use the appropriate tools.

lsblk -f
 sudo lvs -a -o lv_name,vg_name,lv_size,segtype,data_percent,metadata_percent,pool_lv,origin
 sudo xfs_quota -x -c 'report -h' /var/log 2>/dev/null || true
 sudo btrfs filesystem usage /var/log 2>/dev/null || true

Thin pool data_percent or metadata_percent near 100% is a separate critical event; deleting one file in the mount won't guarantee recovery. Expanding, merging, or deleting snapshots carries data risk—must verify dependencies and follow storage change procedures.

Fix Log Rotation to Prevent Recurrence

The correct logrotate strategy depends on whether the application supports reopen. If it supports a signal, prefer rename then notify reopen; copytruncate copies then truncates the original file—the app doesn't need reopen, but the copy window may lose or duplicate logs, and copying 200GB generates huge I/O, unsuitable for high-write-rate logs.

Nginx rotation example: rotate then send USR1 to master. Use logrotate -d dry-run first.

/var/log/nginx/*.log {
   daily
   rotate 14
   missingok
   notifempty
   compress
   delaycompress
   sharedscripts
   postrotate
     test ! -s /run/nginx.pid || kill -USR1 "$(cat /run/nginx.pid)"
   endscript
}
sudo logrotate -d /etc/logrotate.conf
 sudo nginx -t
 sudo logrotate -v -f /etc/logrotate.d/nginx
 sudo lsof -nP /var/log/nginx/*.log
-f

forces rotation, has I/O and log switch impact—only in test or maintenance window. Verification points: new log inode opened by process, old file stops growing, compression occurs on schedule, not just rotation file appears.

systemd journal should have limits so it auto-reclaims within capacity threshold. Backup config before change, verify effective config.

# /etc/systemd/journald.conf.d/limits.conf
[Journal]
SystemMaxUse=4G
SystemKeepFree=2G
RuntimeMaxUse=512M
MaxFileSec=1day
sudo systemd-analyze cat-config systemd/journald.conf
 sudo systemctl restart systemd-journald
 journalctl --disk-usage
 journalctl --verify
 sudo journalctl --rotate
 sudo journalctl --vacuum-size=4G
 journalctl --disk-usage

First four verify config and journal integrity; last three reclaim history only after confirming audit retention. Restarting journald usually doesn't restart business but may cause brief log forwarding impact. Rollback by deleting drop-in or restoring backup, then restart journald; don't directly rm journal files.

Container platforms should also set kubelet log rotation, and confirm the current distro/managed platform supports the fields. Config changes affect node-level container log retention; need canary node validation.

# kubelet config snippet
containerLogMaxSize: 50Mi
containerLogMaxFiles: 5

Verification, Postmortem, and Automated Inspection

Space release confirmation requires at least: df usage drops; deleted FDs no longer hold large files; target service healthy; new logs write to correct inode; log rotation next cycle executes; alert recovers and growth rate normal.

df -hT /var/log
 df -ih /var/log
 sudo lsof -nP +L1 | head -n 100
 systemctl --failed
 find /var/log/myapp -maxdepth 1 -type f -printf '%TY-%Tm-%Td %TH:%TM:%TS %s %i %p
' | sort

Periodically collect deleted regular files' allocated blocks and alert on threshold, but inspection scripts must not auto-truncate or restart. The script below deduplicates by device/inode, returns non-zero if total exceeds 1 GiB.

#!/usr/bin/env bash
 set -u

 threshold=${DELETED_FILE_THRESHOLD_BYTES:-1073741824}
 declare -A seen
 total=0

 for link in /proc/[0-9]*/fd/*; do
   target=$(readlink "$link" 2>/dev/null) || continue
   [[ $target == *' (deleted)' ]] || continue
   IFS='|' read -r type dev inode blocks unit <<(stat -Lc '%F|%d|%i|%b|%B' "$link" 2>/dev/null) || continue
   [[ $type == 'regular file' ]] || continue
   key="$dev:$inode"
   [[ -v seen[$key] ]] && continue
   seen[$key]=1
   bytes=$((blocks*unit)); total=$((total+bytes))
   printf 'bytes=%s inode=%s target=%q holder=%s
' \
     "$bytes" "$key" "$target" "$link"
 done

 printf 'deleted_allocated_bytes=%s
' "$total"
 (( total < threshold ))

If /proc is mounted with hidepid, run a controlled root collector instead of relaxing permissions for all users. Alert info should retain device/inode, holding PID, service, first-seen time, and growth rate—not just "deleted file exists".

Postmortem must answer: Who deleted/rotated? Why didn't the app reopen? Why did logs grow to 200GB? Did capacity alert give enough time? What are log retention and audit requirements? Were multiple namespaces or child processes holding FDs? What did emergency ops lose? How to verify next rotation?

"Ghost files" aren't mysterious. rm unlinks the name; the FD retains the object; the filesystem reclaims blocks only after the last reference closes. Reliable handling depends on a complete evidence chain: df vs du difference, lsof / /proc to find holder, device/inode to lock the object, prefer reopen or graceful restart, truncate only after acknowledging irreversible risk, eliminate recurrence via rotation, capacity limits, and monitoring.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

LinuxTroubleshootingSystem AdministrationDisk SpaceLog RotationFile DescriptorslsofGhost Files

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion