Platform Engineering · Lesson 16

Disks, Partitions, and File Systems

A new disk is only a long row of numbered blocks, with no files and no folders. Before an application can write a file, an administrator finds the disk, writes a partition table, creates a file system, mounts it, and makes the mount survive a reboot in /etc/fstab. Each step has one classic mistake: a device name that changes, a missing nofail, or a file system that runs out of inodes while df still shows free space. This lesson takes one data disk from attached to in use, safely.

Difficulty: Intermediate · Know this first: Lesson 11, Lesson 02

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up admin minutes from an attached disk to a disk in use. It is a worked example, not a measurement. The fstab and monitor hops are where one line or one missing alert turns into an outage.

Try it: how many files fit?

On ext4 the inode count is fixed when the file system is made: one inode per bytes-per-inode. Set the disk size, the average file size, and the bytes-per-inode ratio, and see whether space or inodes run out first.

6.6 Minodes
26.2 Mfiles that fit by space
inodesruns out first

Inodes run out first: the disk will report full at about 25% used

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Disk administration grows in four levels: reading what is there, adding a disk safely, choosing and tuning file systems, and managing storage for a fleet.

Basic — Read disks and mounts

At the basic level you can say what is attached and where it is mounted.

  • lsblk -f, df -h, df -i, findmnt.
  • Disk, partition, file system, mount point: four different things.
  • du -sh /var/* | sort -h to find what is using space.

Where it breaks: deleting a big log file that a process still has open frees nothing until the process closes it (lsof +L1 finds them).

Try it: Basic

You delete a 20 GB log but df shows no change. Why?

Now do it: Run sudo lsof +L1 on a busy server.

Intermediate — Add a disk safely

At the intermediate level you add storage without risking the boot.

  • parted /dev/sdX mklabel gpt mkpart data ext4 1MiB 100%.
  • mkfs.ext4 -L data or mkfs.xfs -L data.
  • fstab by UUID with nofail; prove it with umount and mount -a, and findmnt --verify.

Try it: Intermediate

You added a line to fstab. What do you do before you log out?

Now do it: Add a test entry for a loop device in a VM and check it with findmnt --verify.

Advanced — Choose and tune file systems

At the advanced level the file system fits the workload.

  • ext4 versus XFS: XFS for large files and parallel I/O and grows online; ext4 can shrink offline and is the common default.
  • Inodes: mkfs.ext4 -i 4096 for small-file workloads; reserved blocks with tune2fs -m.
  • Checks: e2fsck -f or xfs_repair on an unmounted file system; fstrim or the discard option for SSDs.

Try it: Advanced

A build cache creates 30 million files of 2 KB on a new 200 GB ext4 volume. What should you do at mkfs time?

Now do it: Compute inodes for your largest data volume and compare with df -i.

Master — Storage for a fleet

At the master level disks are provisioned by code and watched.

  • Volumes, file systems, and mounts declared in cloud-init, Ansible, or Terraform; never by hand on one host.
  • Alerts on blocks, inodes, read-only remounts, and SMART or cloud volume health.
  • Growth paths agreed in advance: LVM or cloud volume resize, then online grow.

Trade-off: nofail keeps a host booting without its data disk, and the app must then refuse to start rather than write into the empty mount point on the root disk.

Try it: Master

With nofail, the data disk failed to mount and the app wrote 50 GB into the empty /data directory on the root disk, filling it. What prevents that?

Now do it: Add RequiresMountsFor= to one service that uses a data disk.

Go deeper

Practise every step safely on a loop device: a file that the kernel treats as a disk. Nothing here touches a real disk.

A practice disk

truncate -s 1G disk.img
DEV=$(sudo losetup --find --show disk.img); echo "$DEV"     # e.g. /dev/loop0
sudo parted -s "$DEV" mklabel gpt mkpart data ext4 1MiB 100%
sudo partprobe "$DEV"; lsblk "$DEV"
sudo mkfs.ext4 -q -L practice "$DEV"p1
sudo mkdir -p /mnt/practice && sudo mount "$DEV"p1 /mnt/practice
df -h /mnt/practice; df -i /mnt/practice
sudo blkid "$DEV"p1

An fstab line you can test (by label, with nofail)

# /etc/fstab
LABEL=practice  /mnt/practice  ext4  defaults,noatime,nofail  0  2

sudo umount /mnt/practice && sudo mount -a && findmnt /mnt/practice
sudo findmnt --verify

# clean up: remove the fstab line first
sudo umount /mnt/practice; sudo losetup -d "$DEV"; rm disk.img

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. A routine disk addition stopped a server from booting.

Timeline

  • MondayA second volume is attached for logs. The data volume, listed in fstab as /dev/sdb1, is now discovered as sdc.
  • Saturday 03:00Kernel patching reboots the host. /dev/sdb1 is the new, unformatted log disk; the mount fails and, without nofail, boot stops in emergency mode.
  • Saturday 04:30An engineer gets console access, fixes the line to UUID=, and the host boots.

What changed after

A linter rejects fstab entries by /dev name, data disks get nofail plus RequiresMountsFor= in their services, and every fstab change is tested with mount -a and findmnt --verify in the same change.

Essential commands, with real output

Partition a disk, make a file system, check it, and mount it. Here the disk is a 200 MB file, so every command runs without root and without touching a real disk; mounting needs root, so that part is shown. There are 16 commands below, in the order you would use them. Each one shows what it printed when we ran it, so you can compare your screen with it; where the output depends on your machine, the note tells you what to look for.

Set up a practice folder

Every command below works on these files, so run this first, in an empty folder (mkdir -p ~/practice && cd ~/practice). It only creates files there.

truncate -s 200M disk.img
truncate -s 64M fs.img

Partition the disk

Write a GPT partition table from a script: one 64 MB Linux partition and one 32 MB swap partition. Scripts beat clicking: they can be reviewed and rerun.

$ printf "label: gpt\nlabel-id: 0B5E7D2A-1111-4222-8333-444455556666\nsize=64M, type=linux, name=data\nsize=32M, type=swap, name=swap\n" | sfdisk -q disk.img && echo "partitioned"
partitioned

Read the table back: each partition's first and last sector, size, and type.

$ sfdisk -l disk.img
Disk disk.img: 200 MiB, 209715200 bytes, 409600 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 0B5E7D2A-1111-4222-8333-444455556666

Device      Start    End Sectors Size Type
disk.img1    2048 133119  131072  64M Linux filesystem
disk.img2  133120 198655   65536  32M Linux swap

Dump the table as a script (here cut to start, size, and type); save the full dump before changing a real disk, and sfdisk disk < saved restores it.

$ sfdisk -d disk.img | grep "^disk.img" | cut -d, -f1-3
disk.img1 : start=        2048, size=      131072, type=0FC63DAF-8483-4772-8E79-3D69D8477DE4
disk.img2 : start=      133120, size=       65536, type=0657FD6D-A4AB-43C4-84E5-0933C84B4F4F

Partition sizes in 512-byte sectors: 64 MB is 131072 sectors, as the table shows.

$ echo $(( 64 * 1024 * 1024 / 512 )) sectors
131072 sectors

On a real machine: every disk and partition.

$ lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINTS,UUID

Make and check a file system

Make an ext4 file system with a label and a fixed UUID. On a real disk the target is a partition, like /dev/sdb1.

$ mkfs.ext4 -q -F -L labdata -U 11111111-2222-3333-4444-555555555555 fs.img && echo "made ext4"
made ext4

The superblock: label, UUID, size in blocks, and how many inodes (one per file) it can hold.

$ dumpe2fs -h fs.img 2>/dev/null | grep -E "^(Filesystem volume name|Filesystem UUID|Block count|Block size|Inode count|Reserved block count):"
Filesystem volume name:   labdata
Filesystem UUID:          11111111-2222-3333-4444-555555555555
Inode count:              16384
Block count:              16384
Reserved block count:     819
Block size:               4096

Check the file system read-only (-n). Never run fsck on a mounted file system.

$ e2fsck -fn fs.img
e2fsck 1.47.2 (1-Jan-2025)
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
labdata: 12/16384 files (8.3% non-contiguous), 2097/16384 blocks

ext4 keeps 5% of blocks for root by default; on a big data disk, 1% is plenty.

$ tune2fs -m 1 fs.img | tail -1 && dumpe2fs -h fs.img 2>/dev/null | grep "^Reserved block count"
Setting reserved blocks percentage to 1% (163 blocks)
Reserved block count:     163

Read and change the label.

$ e2label fs.img; tune2fs -L appdata fs.img >/dev/null; e2label fs.img
labdata
appdata

XFS is the other common choice; it can grow but never shrink.

$ sudo mkfs.xfs -L logs /dev/sdc1

Mount it

Mount the image (through a loop device) with noatime, which skips a write on every read.

$ sudo mkdir -p /mnt/lab && sudo mount -o loop,noatime fs.img /mnt/lab && findmnt /mnt/lab

Mount at boot by UUID. nofail lets the machine boot if the disk is missing.

$ echo "UUID=11111111-2222-3333-4444-555555555555 /mnt/lab ext4 defaults,noatime,nofail 0 2" | sudo tee -a /etc/fstab

Check fstab, then mount everything in it, before you reboot: a bad line can stop the boot.

$ sudo findmnt --verify && sudo mount -a

If unmount says "target is busy", list who has files open there.

$ sudo umount /mnt/lab || sudo lsof +f -- /mnt/lab

Space and inodes on the new file system.

$ df -hT /mnt/lab; df -i /mnt/lab

Practice: write the command yourself

Each task uses the practice folder. Try it first, then open the solution to compare; there is usually more than one right answer.

  1. Make a GPT table on disk.img with three 40 MB Linux partitions (with any fixed label-id) and print the partition lines.

    Show a solution
    $ printf "label: gpt\nlabel-id: 0B5E7D2A-1111-4222-8333-444455556666\nsize=40M, type=linux\nsize=40M, type=linux\nsize=40M, type=linux\n" | sfdisk -q disk.img && sfdisk -l disk.img | grep "^disk.img"
    disk.img1    2048  83967   81920  40M Linux filesystem
    disk.img2   83968 165887   81920  40M Linux filesystem
    disk.img3  165888 247807   81920  40M Linux filesystem
  2. Make an ext4 file system on fs.img with the label backups and print the label back.

    Show a solution
    $ mkfs.ext4 -q -F -L backups fs.img && e2label fs.img
    backups
  3. Make an ext4 file system on fs.img with 1% reserved blocks from the start (-m 1) and print the reserved block count.

    Show a solution
    $ mkfs.ext4 -q -F -m 1 fs.img && dumpe2fs -h fs.img 2>/dev/null | grep "^Reserved block count"
    Reserved block count:     163
  4. How many 512-byte sectors are in a 2 TiB disk? Compute it in the shell.

    Show a solution
    $ echo $(( 2 * 1024 * 1024 * 1024 * 1024 / 512 ))
    4294967296

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: A Linux VM or a spare machine where you have sudo (a cloud VM, Multipass, or VirtualBox). Some commands change the system; do not run them on a shared server. Disk commands here use loop devices (files acting as disks), so no real disk is touched.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Make a 1 GB practice disk from a file and attach it.

    truncate -s 1G lab-disk.img
    DEV=$(sudo losetup --find --show lab-disk.img); echo "practice disk: $DEV"; lsblk "$DEV"
  2. Write a GPT table and one aligned partition, then a file system.

    sudo parted -s "$DEV" mklabel gpt mkpart data ext4 1MiB 100%
    sudo partprobe "$DEV"; sudo mkfs.ext4 -q -L labdata "$DEV"p1; lsblk -f "$DEV"
  3. Mount it, check blocks and inodes, and find its UUID.

    sudo mkdir -p /mnt/labdata && sudo mount "$DEV"p1 /mnt/labdata
    df -h /mnt/labdata; df -i /mnt/labdata; sudo blkid "$DEV"p1
  4. Test an fstab line safely with findmnt --verify, then clean up.

    echo "LABEL=labdata /mnt/labdata ext4 defaults,noatime,nofail 0 2" | sudo tee -a /etc/fstab >/dev/null
    sudo findmnt --verify --tab-file /etc/fstab | tail -3
    sudo sed -i "/LABEL=labdata/d" /etc/fstab; sudo umount /mnt/labdata; sudo losetup -d "$DEV"; rm lab-disk.img

2. Python: fstab_lint.py

This program lints fstab lines the way a careful reviewer would: device names instead of UUIDs, missing nofail on data disks, and bad field counts. Save it as fstab_lint.py, then run it.

# fstab_lint.py
fstab = """UUID=3f2a9c1e-8b7d-4e21-9a55-0c1d2e3f4a5b /          ext4 defaults        0 1
UUID=7b1c...efi                              /boot/efi  vfat umask=0077       0 1
/dev/sdb1                                    /data      ext4 defaults,noatime 0 2
LABEL=logs                                   /var/log   xfs  defaults         0 2
/dev/disk/by-id/nvme-Samsung_SSD_970-part1   /scratch   ext4 nofail           0 0
tmpfs /tmp tmpfs"""
SYSTEM = {"/", "/boot", "/boot/efi", "/usr", "/var"}

for n, line in enumerate(fstab.splitlines(), 1):
    fields = line.split()
    problems = []
    if len(fields) != 6:
        problems.append(f"{len(fields)} fields, expected 6")
    else:
        spec, mount, fstype, opts = fields[:4]
        if spec.startswith("/dev/sd") or spec.startswith("/dev/nvme") or spec.startswith("/dev/vd"):
            problems.append("device name can change between boots: use UUID= or LABEL=")
        if mount not in SYSTEM and "nofail" not in opts.split(","):
            problems.append("data disk without nofail: a missing disk stops the boot")
    print(f"line {n}: {'ok' if not problems else '; '.join(problems)}")

Run it, and you should see this output:

$ python3 fstab_lint.py
line 1: ok
line 2: ok
line 3: device name can change between boots: use UUID= or LABEL=; data disk without nofail: a missing disk stops the boot
line 4: data disk without nofail: a missing disk stops the boot
line 5: ok
line 6: 3 fields, expected 6

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/disks-partitions-and-filesystems && cd ~/labs/disks-partitions-and-filesystems) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Disks, Partitions, and File Systems", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'Make a 1 GB practice disk from a file and attach it.'
  'Write a GPT table and one aligned partition, then a file system.'
  'Mount it, check blocks and inodes, and find its UUID.'
  'Test an fstab line safely with findmnt --verify, then clean up.'
)

step_1() {
truncate -s 1G lab-disk.img
DEV=$(sudo losetup --find --show lab-disk.img); echo "practice disk: $DEV"; lsblk "$DEV"
}

step_2() {
sudo parted -s "$DEV" mklabel gpt mkpart data ext4 1MiB 100%
sudo partprobe "$DEV"; sudo mkfs.ext4 -q -L labdata "$DEV"p1; lsblk -f "$DEV"
}

step_3() {
sudo mkdir -p /mnt/labdata && sudo mount "$DEV"p1 /mnt/labdata
df -h /mnt/labdata; df -i /mnt/labdata; sudo blkid "$DEV"p1
}

step_4() {
echo "LABEL=labdata /mnt/labdata ext4 defaults,noatime,nofail 0 2" | sudo tee -a /etc/fstab >/dev/null
sudo findmnt --verify --tab-file /etc/fstab | tail -3
sudo sed -i "/LABEL=labdata/d" /etc/fstab; sudo umount /mnt/labdata; sudo losetup -d "$DEV"; rm lab-disk.img
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Add a 500 GB data volume to 20 application servers that store user uploads and a thumbnail cache.

Clarifying questions to ask

Which file system and inode ratio? How do the mounts survive reboots and missing disks? What stops the app writing to the root disk if the mount fails? What do you alert on?

Rough sizing

Say uploads average 2 MB, thumbnails 8 KB, 20 million thumbnails per server over a year.

Shape of the answer

GPT with one partition (or LVM for growth); XFS, or ext4 with -i 8192 for the thumbnails; fstab by UUID with nofail and noatime,nodev,nosuid; RequiresMountsFor=/data in the app unit; ownership app:app 750; alerts on blocks and inodes at 80 and 90 percent; all of it in configuration management.

Trade-offs to name

XFS avoids inode planning and cannot shrink; ext4 can shrink offline but needs the inode ratio right up front. nofail keeps hosts booting but needs the service guard so data does not land on the root disk.

Saved on this device, in this browser.
Next in this series · Lesson 17
LVM and RAID in Practice: Grow, Snapshot, Replace a Disk

Two storage jobs come up on every long-lived server: a volume is nearly full and must grow without downtime, and a disk in a mirror dies and must be replaced without losing data.

Go to Lesson 17 →

Or browse the full course from the Lessons index.