# Disks and filesystems: add, mount, grow and repair

How disks, partitions, filesystems and mount points fit together, how to add a new disk and mount it permanently with fstab, grow storage with LVM, add swap, and check a filesystem safely.

Course: [Linux & Bash for DevOps](https://devops.rajeev.pro/courses/linux), lesson 11. About 40 minutes, intermediate. Source: https://devops.rajeev.pro/courses/linux/11-disks-filesystems

## What you will learn

- Explain the storage stack from disk to mount point, and read lsblk, df -T and findmnt
- Partition a new disk, create a filesystem and mount it
- Mount a disk at every boot with a UUID in /etc/fstab, and test it before rebooting
- Explain inodes, and why a disk can be "full" with free space
- Create and grow LVM volumes, and resize the filesystem with them
- Add swap, and check or repair a filesystem without damaging it

## The storage stack

**Why this lesson matters.** "Disk full" is one of the most common ways a server breaks: logs stop
being written, databases refuse writes, deploys fail half-way. The fix usually means adding a disk
or growing one, and that's where people get nervous, because one wrong command can wipe the wrong
disk. This lesson takes you from a brand-new empty disk to one that's formatted, mounted and still
there after a reboot. It also shows how to grow storage later without downtime.

Linux storage is layers. Once you can name the layer you're looking at, every command makes
sense:

> **Figure.** The storage stack from bottom to top. A disk, such as nvme1n1. Partitions on it, such as nvme1n1p1. Optionally LVM: partitions become physical volumes, grouped into a volume group, carved into logical volumes you can grow. A filesystem, such as ext4 or XFS, is created on a partition or logical volume. It is mounted at a folder, such as /data, where programs use it. /etc/fstab mounts it at every boot.
>
> Disk, partition, (LVM), filesystem, mount point. Most problems live at one layer.

```sh
$ lsblk                                  # disks and partitions, as a tree
NAME         MAJ:MIN RM  SIZE RO TYPE MOUNTPOINTS
nvme0n1      259:0    0   40G  0 disk
├─nvme0n1p1  259:1    0 39.9G  0 part /
└─nvme0n1p15 259:2    0  106M  0 part /boot/efi
nvme1n1      259:3    0   50G  0 disk
$ lsblk -f                               # plus filesystem type and UUID
$ df -Th                                 # mounted filesystems: type, size, use
$ findmnt /                              # how one mount point is mounted, with options
TARGET SOURCE         FSTYPE OPTIONS
/      /dev/nvme0n1p1 ext4   rw,relatime,discard,errors=remount-ro
```

Here `nvme1n1` is a new, empty 50 GB disk: no partitions, nothing mounted. Disk names are
`sda`, `sdb` on many machines, `vda` on some VMs and `nvme0n1` on newer hardware and cloud
instances.

## Filesystems and inodes

A **filesystem** organises a partition into files and folders. The two you'll meet on servers:

|                    | ext4              | XFS                       |
| ------------------ | ----------------- | ------------------------- |
| Default on         | Ubuntu, Debian    | RHEL, Rocky, Amazon Linux |
| Grow while mounted | yes               | yes                       |
| Shrink             | yes (unmounted)   | no                        |
| Check / repair     | `e2fsck` (`fsck`) | `xfs_repair`              |
| Tune               | `tune2fs`         | `xfs_admin`               |

Every file has an **inode**: a record of its owner, permissions, size and where its data is. Its
name lives in the folder; the inode holds the rest (you saw inode numbers with `ls -i` in the
_Working with files_ lesson). On ext4 the number of inodes is fixed when the filesystem is made:

```sh
$ df -i /
Filesystem      Inodes  IUsed   IFree IUse% Mounted on
/dev/nvme0n1p1 2621440 2621440       0  100% /
```

That's a disk that is "full" with gigabytes free: millions of tiny files (sessions, cache, mail)
used every inode. Find the folders holding the most entries:

```sh
$ sudo du --inodes -x / 2>/dev/null | sort -n | tail -5    # inode use per folder, biggest last
```

## Adding a new disk

A newly attached disk is only a block device. Linux cannot store ordinary files on it until you partition or
otherwise prepare it, create a filesystem, and mount that filesystem at a directory. Each step changes a
different layer and must target the intended device.

```sh
$ sudo parted /dev/nvme1n1 --script mklabel gpt mkpart data ext4 0% 100%   # one partition, whole disk
$ lsblk /dev/nvme1n1
NAME      MAJ:MIN RM SIZE RO TYPE MOUNTPOINTS
nvme1n1   259:3    0  50G  0 disk
└─nvme1n1p1 259:4  0  50G  0 part
$ sudo mkfs.ext4 -L data /dev/nvme1n1p1     # create the filesystem (-L sets a label)
$ sudo mkdir -p /data
$ sudo mount /dev/nvme1n1p1 /data           # mount it now
$ df -h /data
```

`fdisk` (MBR or GPT) and `gdisk` (GPT) do the same job interactively. Use **GPT** for new disks:
MBR can't handle disks over 2 TB.

First identify the new device with `lsblk` and confirm its size and mount points. Then create a partition
table and partition, format that partition, create a mount point and mount it. `mkfs` writes new filesystem
metadata and destroys prior contents, so never run it on a device until you have confirmed the exact name.

> **Check the disk name twice.** `mkfs` and `parted` destroy whatever is on the device you name. Run `lsblk` first, confirm the size and that nothing is mounted, and copy the exact name. Formatting `nvme0n1p1` instead of `nvme1n1p1` erases the operating system.

> **Video.** [Linux Crash Course - Everything You Need to Know for Formatting and Mounting Disks](https://www.youtube.com/watch?v=2Z6ouBYfZr8) (Learn Linux TV)

## Mounting: now and at every boot

**What mounting means.** Windows gives every disk a letter: `C:`, `D:`. Linux doesn't. There is one
single folder tree starting at `/`, and you attach a disk _into_ that tree at a folder of your
choice. That folder is the **mount point**. After `mount /dev/nvme1n1p1 /data`, everything you write
into `/data` actually goes onto the new disk, while `/etc` and `/home` stay on the original one. To
programs it's all just folders. Unmount it and `/data` is an ordinary empty folder again.

> **Figure.** One folder tree starting at slash, with etc, home, var and data. etc, home and var live on the system disk nvme0n1p1. data is a mount point: after sudo mount /dev/nvme1n1p1 /data, everything under /data is stored on the new 50 GB data disk.
>
> The system disk holds most of the tree. The new disk appears at /data, the folder it is mounted on.

`mount` lasts until the next reboot. To mount at every boot, add a line to `/etc/fstab`, using
the filesystem's **UUID** (device names can change when disks are added):

```sh
$ sudo blkid /dev/nvme1n1p1
/dev/nvme1n1p1: LABEL="data" UUID="3f9c2a1e-8b7d-4c1a-9e2f-6a5b4c3d2e1f" BLOCK_SIZE="4096" TYPE="ext4"
```

```text
# /etc/fstab
# <what>                                    <where>  <type>  <options>          <dump> <fsck order>
UUID=3f9c2a1e-8b7d-4c1a-9e2f-6a5b4c3d2e1f   /data    ext4    defaults,nofail    0      2
```

| Field      | Means                                                                           |
| ---------- | ------------------------------------------------------------------------------- |
| what       | `UUID=…` (or `LABEL=data`)                                                      |
| where      | the mount point folder                                                          |
| type       | `ext4`, `xfs`, `swap`…                                                          |
| options    | `defaults`; `nofail` boots even if this disk is missing; `noatime` saves writes |
| dump       | `0` (nobody uses dump any more)                                                 |
| fsck order | `1` for `/`, `2` for other filesystems, `0` never check                         |

```sh
$ sudo umount /data
$ sudo mount -a                  # mount everything in fstab now: errors show here, not at boot
$ sudo findmnt --verify          # check fstab for mistakes
$ findmnt /data
```

> **In production: never reboot on an untested fstab.** A wrong `/etc/fstab` line can stop the boot and drop the server into emergency mode, which on a cloud VM often means no SSH at all. Always run `sudo mount -a` and `findmnt --verify` after editing it, and use `nofail` for data disks, so a missing disk doesn't block the boot.

> **Video.** [Linux Crash Course - The /etc/fstab file](https://www.youtube.com/watch?v=A7xH74o6kY0) (Learn Linux TV)

`umount` fails with "target is busy" while something uses the mount: find what with
`sudo lsof +D /data` or `sudo fuser -vm /data`, and stop it first.

After editing fstab, run `mount -a` and `findmnt --verify` before rebooting. The `nofail` option can let a
server boot when an optional data disk is missing, but it does not make a broken mount harmless to the
application. A common mistake is copying a UUID from another machine or omitting the mount point directory.

## LVM: storage you can grow

With plain partitions, a full disk means moving data. **LVM** (Logical Volume Manager) adds a
flexible layer: disks become **physical volumes** (PV), pooled into a **volume group** (VG), from
which you cut **logical volumes** (LV). Need more space? Add a disk to the group and grow the volume,
while it's mounted.

```sh
$ sudo pvcreate /dev/nvme1n1                  # 1. make the disk a physical volume
$ sudo vgcreate data /dev/nvme1n1             # 2. a volume group called data
$ sudo lvcreate -n app -L 20G data            # 3. a 20 GB logical volume: /dev/data/app
$ sudo mkfs.ext4 /dev/data/app && sudo mount /dev/data/app /srv/app
$ sudo pvs && sudo vgs && sudo lvs            # what you have, layer by layer
$ sudo lvextend -r -L +10G /dev/data/app      # later: grow by 10 GB, filesystem included
$ sudo vgextend data /dev/nvme2n1             # out of room? add another disk to the group
```

`-r` on `lvextend` resizes the filesystem in the same step; without it, the volume grows but the
filesystem doesn't, and `df` shows no change. Cloud disks often grow without LVM too: resize the
disk in the console, then `sudo growpart /dev/nvme0n1 1` and `sudo resize2fs /dev/nvme0n1p1`
(`xfs_growfs /` for XFS).

> **Video.** [Linux Logical Volume Manager (LVM) Deep Dive Tutorial](https://www.youtube.com/watch?v=MeltFN-bXrQ) (Learn Linux TV)

## Swap

**The problem it solves.** When a server runs out of RAM, the kernel has to free some immediately.
Without swap, its only option is the **OOM killer** ("out of memory"): it picks a process, often your
biggest one, such as the database, and kills it.

**How swap helps.** Swap is disk space used as overflow memory. When RAM is tight, the kernel moves
memory pages that haven't been touched for a while (an idle part of a program, say) out to the swap
file, and frees that RAM for whatever needs it now. If the program touches those pages again, they're
read back from disk. Disk is thousands of times slower than RAM, so swap is a safety cushion for
short spikes, not extra memory to plan with.

A small swap file is enough for most servers:

```sh
$ sudo fallocate -l 2G /swapfile
$ sudo chmod 600 /swapfile                    # only root may read it: it holds memory contents
$ sudo mkswap /swapfile && sudo swapon /swapfile
$ swapon --show
NAME      TYPE SIZE USED PRIO
/swapfile file   2G   0B   -2
$ echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab   # keep it after reboot
```

Constant swapping (`free -h` showing swap use growing, high `%wa` in `top`) means the server needs
more RAM or a lighter workload, not more swap.

Use a modest swap file when the workload benefits from a safety margin and the storage cost is acceptable.
Protect it because it may contain memory contents, and monitor how often the system reads and writes it. A
common mistake is increasing swap to hide a steady memory leak; investigate the process and workload instead.

## Checking and repairing

Filesystem check tools look for structural damage and, in some cases, repair it. Run them only when the
filesystem is unmounted; checking a mounted filesystem can report inconsistent data or cause damage.
Different filesystem types have different repair tools, so confirm the type and device first.

```sh
$ sudo umount /data                            # never check a mounted filesystem
$ sudo e2fsck -f /dev/nvme1n1p1                # ext4 (fsck picks the right tool too)
$ sudo xfs_repair /dev/data/app                # XFS
$ sudo tune2fs -l /dev/nvme1n1p1 | grep -i "mount count\|state"   # ext4 health info
```

Filesystems mounted at boot (`/`) are checked automatically when needed. For a damaged root
filesystem you boot from a rescue image, or on a cloud VM attach the disk to another instance and
check it there. `dmesg` and `journalctl -k` show disk errors (`I/O error`, `EXT4-fs error`): on
physical hardware, that's often the disk itself failing, and the fix is a backup and a new disk.

Take a current backup before a repair that may change metadata. For a damaged root filesystem, boot from
rescue media or attach the disk to a healthy system and inspect it there. `fsck` is a dispatcher for tools on
some distributions, but the correct command depends on ext4, XFS or another filesystem. A common mistake is
running `e2fsck` on a mounted root volume or on an XFS filesystem.

## Mission: Add a data disk the safe way

A new empty disk is attached to the server for the app's uploads. Create a filesystem on it, mount it at /data so it survives reboots, and prove the fstab line works before any reboot. Practise on a file-backed disk so nothing real is at risk.

- You need: A Linux VM where you have sudo
- You'll have: /data mounted from /etc/fstab

```sh
$ truncate -s 1G ~/disk.img                          # a fake 1 GB disk, safe to practise on
$ LOOP=$(sudo losetup -f --show ~/disk.img) && echo $LOOP
/dev/loop0
$ sudo mkfs.ext4 -q -L data $LOOP
$ UUID=$(sudo blkid -s UUID -o value $LOOP) && echo $UUID
3f9c2a1e-8b7d-4c1a-9e2f-6a5b4c3d2e1f
$ sudo mkdir -p /data
$ echo "UUID=$UUID /data ext4 defaults,nofail 0 2" | sudo tee -a /etc/fstab
$ sudo mount -a && sudo findmnt --verify && findmnt /data
TARGET SOURCE     FSTYPE OPTIONS
/data  /dev/loop0 ext4   rw,relatime
$ echo "uploads work" | sudo tee /data/test.txt
```

`mount -a` mounting `/data` from the fstab line is your proof it will work at boot. On a real disk,
skip `truncate` and `losetup` and use its name from `lsblk` instead. To clean up the practice:
`sudo umount /data`, remove the line from `/etc/fstab`, and `sudo losetup -d /dev/loop0`.

## Try it

- Run `lsblk -f` and name each disk, its filesystem type and where it's mounted.
- Compare `df -h` with `df -i` on the same machine.
- Create a 64 MB file with `truncate -s 64M disk.img`, make an ext4 filesystem on it with `mkfs.ext4`, and read its UUID with `blkid`.
- On a VM, mount that image with `sudo mount -o loop disk.img /mnt/test` and write a file to it.
- Add a line for it in `/etc/fstab` using its UUID, then check the file with `sudo mount -a` and `findmnt --verify`.
- Run `swapon --show` and `free -h` to see the swap you have.

## Quiz

1. Why put UUID=… instead of /dev/sdb1 in /etc/fstab?
   - UUIDs are shorter
   - **Device names can change between boots when disks are added or reordered; a UUID always points at the same filesystem** (answer)
   - fstab requires UUIDs
   Why: The kernel names disks in the order it finds them. Add a disk and yesterday's /dev/sdb may be today's /dev/sdc, mounting the wrong data or none at all.

2. You edited /etc/fstab. What do you run before rebooting?
   - Nothing, reboot to test
   - **sudo mount -a (and findmnt --verify), so a mistake shows now instead of stopping the boot** (answer)
   - sudo fsck /
   Why: A wrong fstab line can drop the server into emergency mode at boot, which on a cloud VM can mean no SSH. mount -a tries every line now, while you can still fix it.

3. df -h says 40% used, but you get "No space left on device". What's likely?
   - The disk is broken
   - **The filesystem ran out of inodes, usually from millions of tiny files; check df -i** (answer)
   - df is wrong
   Why: Every file needs an inode, and their number is fixed when ext4 is created. Session files, cache entries or mail queues can use them all up while plenty of blocks are free.

4. The app's LVM volume is full and the volume group has free space. What grows it online?
   - **sudo lvextend -r -L +20G /dev/data/app** (answer)
   - Reformat it larger
   - sudo fdisk /dev/data/app
   Why: lvextend adds space to the volume, and -r resizes the filesystem on it in the same step. ext4 and XFS can both grow while mounted.

5. When is it safe to run fsck on a filesystem?
   - Any time
   - **Only when it is unmounted (or read-only), for example from a rescue system or at boot** (answer)
   - Only while it is mounted
   Why: fsck on a mounted, changing filesystem can corrupt it. Unmount first, or let the system check it at boot.

## Resources

- [lsblk(8) manual](https://manpages.ubuntu.com/manpages/noble/man8/lsblk.8.html) (Ubuntu manpages)
- [fstab(5): the format of /etc/fstab](https://manpages.ubuntu.com/manpages/noble/man5/fstab.5.html) (Ubuntu manpages)
- [lvm(8): an overview of LVM](https://manpages.ubuntu.com/manpages/noble/man8/lvm.8.html) (Ubuntu manpages)
- [lvextend(8): grow a logical volume](https://manpages.ubuntu.com/manpages/noble/man8/lvextend.8.html) (Ubuntu manpages)
- [LPIC-1 objectives 102.1, 104.1, 104.2 and 104.3](https://wiki.lpi.org/wiki/LPIC-1_Objectives_V5.0) (Linux Professional Institute)
