ubuntu, updated

Disk full: find and free space

The disk is at 100% and you don't know why: find what uses the space, the cases du can't see, and the cleanups that are safe.

First 60 seconds

df -hT -x tmpfs -x squashfs     # which file system is full? (skip RAM disks and snaps)
df -i                           # inodes: "No space left" with free GB means this is at 100%

Note the mount point of the full file system (/, /var, /data…). Every search below stays on that one file system with -x / -xdev.

/ at 100% and things are breaking? Win some room first, analyse after:

sudo journalctl --vacuum-size=200M          # shrink the journal
sudo apt clean                              # drop downloaded .deb files
sudo truncate -s 0 /var/log/huge.log        # empty a runaway log in place

Empty a log with truncate (or : > file), not rm: the service keeps writing to a deleted file and the space is not freed (see below).

Find what uses the space

Drill down level by level, always into the biggest folder:

sudo du -xh --max-depth=1 / 2>/dev/null | sort -h | tail       # biggest folders on /
sudo du -xh --max-depth=1 /var 2>/dev/null | sort -h | tail    # then the winner, and so on

Faster and interactive: ncdu (keys and options in lsof, ss and ncdu).

sudo apt install ncdu
sudo ncdu -x /                  # -x: stay on this file system

Biggest single files and what grew recently:

# 20 biggest files over 500 MB, human readable
sudo find / -xdev -type f -size +500M -printf '%s\t%p\n' | sort -n | numfmt --field=1 --to=iec | tail -20

# files over 50 MB changed in the last hour: who is writing right now?
sudo find / -xdev -type f -mmin -60 -size +50M -printf '%s\t%TT\t%p\n' | numfmt --field=1 --to=iec

Usual suspects:

PathTypically
/var/log, /var/log/journalrunaway logs, journal without size limit
/var/lib/dockerimages, build cache, container logs
/var/cache/apt/archivesdownloaded packages
/var/lib/snapdold snap revisions
/bootold kernels (often a small separate partition)
/var/crash, /var/lib/systemd/coredumpcrash reports, core dumps
/home, /rootforgotten backups, ISOs, .cache
/tmp, /var/tmpleftovers from scripts and installers

Space used but du finds nothing

df says full, du adds up to far less. Four causes:

Deleted files still held open

A process keeps writing to a file that was deleted. The name is gone, the blocks are not.

sudo lsof +L1                   # open files with link count 0 (deleted)
sudo lsof +L1 | sort -k7 -n | tail    # sorted by SIZE/OFF

Free it by restarting the process (sudo systemctl restart SERVICE). No restart possible? Truncate through the process’s file descriptor. PID and FD come from the lsof columns, drop the letter (4w → 4):

sudo truncate -s 0 /proc/1234/fd/4

Files hidden under a mount point

Something wrote into /data while the disk was not mounted. Now the disk is mounted on top and those files are invisible, but still use space on /. Look underneath with a bind mount:

sudo mkdir -p /mnt/rootfs
sudo mount --bind / /mnt/rootfs                     # / without the mounts on top
sudo du -xh --max-depth=1 /mnt/rootfs/data | sort -h
sudo umount /mnt/rootfs

Inodes full

df -i at 100%: millions of tiny files (session files, mail queue, cache). Count files instead of bytes:

sudo du --inodes -x --max-depth=1 / 2>/dev/null | sort -n | tail     # then drill down

Common culprits: /var/lib/php/sessions, /var/spool/postfix, app cache folders. Delete in bulk with find ... -delete (an rm * fails with “argument list too long”).

Reserved blocks (ext4)

ext4 keeps 5% for root, so Size - Used is bigger than Avail. Fine for /, a waste on a large data disk:

sudo tune2fs -l /dev/sdb1 | grep -i 'reserved block count'
sudo tune2fs -m 1 /dev/sdb1     # data disk only: reserve 1% instead of 5%

Safe cleanups

Check what each one frees first, then run it.

apt and old kernels

WhatCommand
Size of the package cachedu -sh /var/cache/apt/archives
Delete downloaded .deb filessudo apt clean
Remove unused dependencies and old kernelssudo apt autoremove --purge
Purge leftover config of removed packagessudo apt purge '~c'
Installed kernels / running kerneldpkg -l 'linux-image-*' | grep ^ii / uname -r

autoremove keeps the running kernel and the one before it. /boot full and apt itself fails? Run sudo apt -f install after autoremove; never delete files in /boot by hand.

journald

WhatCommand
Current sizejournalctl --disk-usage
Shrink to 500 MB nowsudo journalctl --vacuum-size=500M
Delete entries older than 14 dayssudo journalctl --vacuum-time=14d

Vacuum is one-off. Make the limit permanent:

# /etc/systemd/journald.conf.d/size.conf
[Journal]
SystemMaxUse=500M
sudo systemctl restart systemd-journald

More in journalctl in depth.

Old log files

sudo du -sh /var/log/* 2>/dev/null | sort -h | tail             # biggest logs
sudo find /var/log -type f \( -name '*.gz' -o -name '*.[0-9]' \) -mtime +30 -delete   # rotated logs older than 30 days
sudo logrotate -d /etc/logrotate.conf                            # dry run: does rotation work at all?
sudo logrotate -f /etc/logrotate.d/nginx                         # rotate one app now

One log keeps growing? It has no rule in /etc/logrotate.d/, or the app ignores the rotation (use copytruncate in its rule).

Snap

Snap keeps old revisions of every snap (default: 2 inactive plus the current).

WhatCommand
Show all revisionssnap list --all
Keep only 2 revisions in futuresudo snap set system refresh.retain=2

Remove all disabled revisions now:

snap list --all | awk '/disabled/ {print $1, $3}' |
  while read -r name rev; do sudo snap remove "$name" --revision="$rev"; done

Docker

The short version. Details, filters and log rotation: Docker cleanup.

WhatCommand
What uses the spacedocker system df (-v per image, container, volume)
Stopped containers, unused networks, dangling images, build cachedocker system prune
Same, plus all images not used by a containerdocker system prune -a
Images unused for over a weekdocker image prune -a --filter "until=168h"
Build cache onlydocker builder prune
Biggest container logssudo du -sh /var/lib/docker/containers/*/*-json.log | sort -h
Empty one container logsudo truncate -s 0 /var/lib/docker/containers/ID/ID-json.log

docker system prune --volumes also deletes unused volumes, i.e. data. Check docker volume ls first. Never delete inside /var/lib/docker by hand.

Cap container logs in /etc/docker/daemon.json (applies to containers created after the change):

{ "log-driver": "json-file", "log-opts": { "max-size": "10m", "max-file": "3" } }
sudo systemctl restart docker

Core dumps and crash reports

WhatCommand
Apport crash reportsls -lh /var/crash
Delete themsudo rm /var/crash/*.crash
systemd core dumpscoredumpctl list, files in /var/lib/systemd/coredump/
Delete themsudo rm /var/lib/systemd/coredump/*

Limit with MaxUse= in /etc/systemd/coredump.conf. A crash report is evidence: look at it before deleting if the crash is not explained.

Temp folders and caches

sudo find /tmp /var/tmp -xdev -type f -mtime +7 -delete    # temp files untouched for 7 days
sudo du -sh /home/*/.cache /root/.cache 2>/dev/null         # per-user caches
pip cache purge                                             # Python package cache
npm cache clean --force                                     # npm cache

systemd-tmpfiles cleans /tmp (10 days) and /var/tmp (30 days) on its own; the manual run is for when you can’t wait.

Don’t delete

PathWhy
/var/lib/dpkg, /var/lib/aptpackage database; apt breaks
/var/lib/docker/* by handcorrupts Docker; use docker ... prune
/var/lib/mysql, /var/lib/postgresqllive database files; use the DB’s own tools
Files in /bootunbootable system; use apt autoremove --purge
/var/log/journal/* by handuse journalctl --vacuum-*
Open log files with rmspace not freed; use truncate

Don’t let it happen again

Write a warning to the journal when a file system crosses 90%:

#!/bin/bash
# /etc/cron.hourly/disk-alert   (no dot in the name, chmod +x)
THRESHOLD=90
df -P -x tmpfs -x devtmpfs -x squashfs -x overlay |
  awk -v t="$THRESHOLD" 'NR>1 && $5+0 >= t {print $6 " at " $5}' |
  while read -r line; do logger -t disk-alert -p user.warning "$line"; done

Check with journalctl -t disk-alert. Swap logger for a mail or webhook call if nobody reads the journal. Running out on a VM anyway? Extend a disk or volume.

§ home
~/knubertus/home/
1,1 Top