Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Part 2 · System administration · Lesson 03 · 40 minutes

Find what fills a disk and free the space

After this lesson you can
  • Read df for space and for inodes, and say which file system is full
  • Use du to find the folder and the files that take the space
  • Explain why df and du can disagree, and free space without risk
Lab files of this lesson (9)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

At 03:00 the monitoring of a file server raises an alarm: "disk 98% full". The backup job has failed, and a database refuses to write. Your lead asks you to find what fills the disk. She also gives a rule: you may name the cause, but you delete nothing until she agrees. You practise on your own system and on a small folder tree that the lesson builds.

Recall

Which column of "free -m" tells you how much memory a new program can get?

available. The column free ignores the memory that the kernel uses for caches, and that memory comes back when a program needs it.

What is an inode, and what does "ls -i" print?

An inode is the record of a file system that holds the owner, the mode, the size and where the data is. A file name points to an inode. ls -i prints the inode number in front of each name.

The idea

A disk can be full in two ways. It can be out of blocks, the units that hold data, or out of inodes, the records that hold the facts of a file. Each file and each directory uses one inode. A folder with a million tiny files can use every inode while it holds almost no data. The disk then refuses to make a new file although the space is free.

df (disk free) answers the first question: which file system is full. du (disk usage) answers the second: which folder holds the data. You use them in this order.

Find what fills a disk
Disk full alertdf -hdf -idu --max-depth=1Go deeperwhich file system?out of blocks or inodes?which folder?pick the biggestrepeat in itDisk full alertdf -hdf -idu --max-depth=1Go deeper12345
  1. Disk full alert → df -h: which file system?
  2. df -h → df -i: out of blocks or inodes?
  3. df -i → du --max-depth=1: which folder?
  4. du --max-depth=1 → Go deeper: pick the biggest
  5. Go deeper → du --max-depth=1: repeat in it

Worked example

1. Read the space of the file systems

df -h (human-readable) shows each file system with its size, use and mount point (where it is attached in the tree). -T adds the type of the file system. Give a path, and df shows only the file system that holds it. The output comes from a test virtual machine. Yours will list other devices.

df -hT /
Filesystem     Type  Size  Used Avail Use% Mounted on
/dev/sda2      ext4   20G  2.6G   17G  14% /

Use% is the number that alarms watch. The type tmpfs is a file system in memory, and overlay is the usual file system of a container. Ignore both when you look for a full disk.

2. Read the inodes

df -i shows the inodes instead of the blocks. IUse% near 100 is the second kind of full disk. This example makes 500 empty files and reads the numbers before and after. The shell expands f{1..500} to the 500 names f1 f2 ... f500, and touch makes an empty file for each. df -i . shows the file system that holds the current folder, here the ext4 device that is mounted on /.

mkdir -p ~/krlab/linux-admin/ino && cd ~/krlab/linux-admin/ino
df -i .
touch f{1..500}
df -i .
find . | wc -l
Filesystem      Inodes IUsed   IFree IUse% Mounted on
/dev/sda2      2557440 43456 2513984    2% /
Filesystem      Inodes IUsed   IFree IUse% Mounted on
/dev/sda2      2557440 43956 2513484    2% /
501

IUsed grew by exactly 500, and the space did not change, because the files are empty. Each name is one inode, so find FOLDER | wc -l counts the inodes of a folder: 500 files and the folder itself make 501. Remove the folder: cd .. && rm -r ino.

3. Measure a folder

Build a small tree to measure. head -c N /dev/urandom takes N bytes of random data, so each file has an exact size.

mkdir -p ~/krlab/linux-admin/disk-demo && cd ~/krlab/linux-admin/disk-demo
mkdir photos notes
head -c 1048576 /dev/urandom > photos/a.jpg
head -c 3145728 /dev/urandom > photos/b.jpg
echo x > notes/tiny.txt
du -sh .
du -h --max-depth=1 .
4.1M	.
4.1M	./photos
8.0K	./notes
4.1M	.
A du command, taken apart
dudisk usage-hsizes in K, M or G--max-depth=1this folder and its children.the folder to measuredudisk usage-hsizes in K, M or G--max-depth=1this folder and its children.the folder to measure

du -s (summary) prints one total for a folder. The total comes last. The folder notes shows 8.0K: 4.0K for the folder itself and 4.0K for the one block of tiny.txt. Raise the number after --max-depth= to look deeper.

4. Sort to find the biggest

sort -r (reverse) puts the biggest number first. Plain sort -n does not understand the letters in 4.0M; sort -h (human numbers) does. head -n 3 keeps the first three lines.

du -h --max-depth=1 . | sort -rh | head -n 3
4.1M	./photos
4.1M	.
8.0K	./notes

This pipe is the tool of the day: du -h --max-depth=1 FOLDER | sort -rh | head. Run it, enter the biggest folder, and run it again.

To find the folder with the most files, and not the most bytes, count the names: find . -type f lists the files, cut -d/ -f2 keeps the first folder of each path, and uniq -c counts them.

find . -type f | cut -d/ -f2 | sort | uniq -c | sort -rn
      2 photos
      1 notes

5. Know what du counts

du counts the blocks that a file uses, and a block is usually 4 KiB. A file of two bytes uses 4.0K. The option --apparent-size counts the bytes of the content instead. A sparse file has holes that take no blocks. truncate -s 1G FILE makes one that looks like 1 GiB.

du -h notes/tiny.txt
du -h --apparent-size notes/tiny.txt
truncate -s 1G sparse.img
ls -lh sparse.img
du -h sparse.img
du -h --apparent-size sparse.img
rm sparse.img
4.0K	notes/tiny.txt
2	notes/tiny.txt
-rw-rw-r-- 1 you you 1.0G Nov 21 19:41 sparse.img
0	sparse.img
1.0G	sparse.img

For "what fills the disk", use plain du. For "how big is this content", use --apparent-size. Virtual machine images and databases are often sparse. On file systems with compression, du shows even less.

6. Understand why df and du disagree

A deleted file is not freed while a process still has it open. df still counts its blocks, and du cannot see it, because it has no name. In bash, exec 3< FILE opens the file as number 3, and exec 3<&- closes it. Every open file of a process appears as a link in /proc/PID/fd.

echo data > gone.txt
exec 3< gone.txt
rm gone.txt
ls -l /proc/$$/fd/3
exec 3<&-
lr-x------ 1 you you 64 Nov 21 19:41 /proc/1689/fd/3 -> /home/you/krlab/linux-admin/disk-demo/gone.txt (deleted)

$$ is the PID of your shell. The word (deleted) shows the case. When a log file of a service is deleted by hand, the space comes back only after the service closes it: restart the service, or end the process (lesson 5).

Why df and du disagree
ShellDiskFolderdfduexec 3< gone.txt keeps it openrm gone.txt removes the namestill counts the blocksfinds no name, counts nothingShellDiskFolderdfdu1234
  1. Shell → Disk: exec 3< gone.txt keeps it open
  2. Shell → Folder: rm gone.txt removes the name
  3. df → Disk: still counts the blocks
  4. du → Folder: finds no name, counts nothing

7. Look at the usual suspects

On a real server the space goes to /var (logs, caches, databases), /home and /tmp. -x (one file system) keeps du from crossing into other mounts. Run it with sudo to read all folders.

sudo du -xh --max-depth=1 /var | sort -rh | head -n 4
sudo journalctl --disk-usage
sudo du -sh /var/cache/apt
1000M	/var
620M	/var/cache
336M	/var/lib
44M	/var/log
Archived and active journals take up 41.2M in the file system.
616M	/var/cache/apt

The journal (lesson 8) and the package cache are safe to shrink with the tools of their own system. sudo apt-get clean empties the package cache, and sudo journalctl --vacuum-size=200M trims the journal to 200 MiB. After apt-get clean the cache of the test machine went from 616M to 32K. A file in /var/lib belongs to a service: do not delete it by hand.

Your turn

Your lead gives you a copy of the file server's data, a small tree with fixed content. Make the folder with mkdir -p ~/krlab/linux-admin/disk, save this script there as build-srv.sh, and run it once with bash ~/krlab/linux-admin/disk/build-srv.sh. It is not the task. tee writes the same input into three files at once (lesson 6 of Part 1). head -c 300000 /dev/zero takes 300,000 zero bytes, and tr '\0' a turns each zero byte into the letter a, so each file has a known size.

disk/build-srv.sh

#!/usr/bin/env bash
# build-srv.sh - builds the tree srv with fixed sizes
set -e
mkdir -p ~/krlab/linux-admin/disk && cd ~/krlab/linux-admin/disk
rm -rf srv && mkdir -p srv/logs srv/cache srv/backups srv/mail
head -c 300000 /dev/zero | tr '\0' a > srv/logs/app.log
head -c 200000 /dev/zero | tr '\0' b > srv/logs/old.log
head -c 2097152 /dev/zero | tr '\0' c > srv/backups/db.dump
head -c 1000 /dev/zero | tr '\0' d | tee srv/cache/c{1..3} > /dev/null
touch srv/mail/m{1..300}
echo "built srv"

Find what takes the space, and what takes the inodes. Use --apparent-size so that your result does not depend on your file system. Do not look at the data: use the tools of the worked example. Then answer.

Last, delete only srv/logs/old.log, as your lead would agree, and check with du that logs is smaller.

Check yourself

df -h shows 40% used, but a program says "No space left on device". What do you check?

The inodes: df -i. A file system can be out of inodes with free blocks left. Also check that you look at the right file system with df -h PATH, and whether a quota or a reserved share of the space applies to your user.

df shows /var at 100%, and du -sh /var shows only half of that. Where is the rest?

Often in a file that was deleted but is still open, so it has no name and du cannot count it. Look for (deleted) in ls -l /proc/*/fd, and restart the service that holds the file. Another cause is files under a mount point that was covered by a later mount.

Why is "sort -n" the wrong tool for "du -h" output?

-n reads only the number and ignores the letter, so 900K sorts above 2.0G. sort -h understands the letters K, M and G. Or use du -k and sort -n.

Your lead says "free some space". Why is it a mistake to run rm -rf on the biggest folder?

The biggest folder can hold the database or the mail of the users. Name the cause first, ask for agreement, and free the part that the system can recreate: caches, rotated logs, old packages. Deleted data does not come back.

Field notes

  • Alarm at 80%, not at 98%. When a file system fills, services fail in strange ways, and the logs that explain the failure cannot be written.
  • Most ext4 file systems keep a small share of blocks for root (5% by default), so that the system can work when users have filled the disk. Do not remove it from /.
  • Stop the growth, not only the symptom. logrotate rotates and compresses logs, and journald has a size limit in /etc/systemd/journald.conf. A cleanup that nobody repeats comes back in a month.
  • ncdu is an interactive version of du and is in the package of the same name. Use it on a server where you look at many folders. It was not run for this lesson.
  • Free space is also a security matter. An attacker or a fault that fills a disk stops logging, and a missing log hides what happened (denial of service, and the loss of the audit trail).
  • A full disk is also a reason for backups. Lesson 5 of Part 3 shows rsync, which copies only what changed.