Linux

Disk Management with LVM

·2 min read

The Logical Volume Manager turns a pile of disks into a pool of storage you can carve up, resize, and snapshot without taking the system down. After thirty seconds of LVM you'll wonder why you ever partitioned disks the old way.

The three layers

LVM has exactly three concepts. Physical Volumes (PVs) are raw block devices — whole disks or partitions — initialized for LVM use. Volume Groups (VGs) pool one or more PVs together. Logical Volumes (LVs) are allocated out of a VG and appear to the system as block devices you can format and mount.

pvcreate /dev/sdb /dev/sdc                # mark two disks as PVs
vgcreate data /dev/sdb /dev/sdc           # pool them into VG "data"
lvcreate -L 100G -n media data            # carve out a 100G LV
mkfs.ext4 /dev/data/media                 # filesystem
mount /dev/data/media /srv/media          # done

Inspecting the layout

pvs    # physical volumes — terse
vgs    # volume groups
lvs    # logical volumes
pvdisplay /dev/sdb        # verbose
vgdisplay data
lvdisplay data/media

Growing online

The whole point of LVM: extending a filesystem without unmounting. If you have free space in the VG:

lvextend -L +20G /dev/data/media
resize2fs /dev/data/media     # ext4; for xfs use xfs_growfs

If the VG is full, add a new PV first:

pvcreate /dev/sdd
vgextend data /dev/sdd
lvextend -l +100%FREE /dev/data/media
resize2fs /dev/data/media

Shrinking (carefully)

Order matters. Shrink the filesystem first, then the LV. ext4 can shrink offline; XFS cannot shrink at all.

umount /srv/media
e2fsck -f /dev/data/media
resize2fs /dev/data/media 80G
lvreduce -L 80G /dev/data/media
mount /dev/data/media /srv/media
Always size the FS smaller than the LV before lvreduce.

If the LV ends up smaller than the FS, you lose data. Take a snapshot before any shrink operation.

Snapshots

LVM snapshots are copy-on-write point-in-time copies. They're cheap to create and ideal for taking a consistent backup of a busy database without locking it.

lvcreate -L 10G -s -n media-snap /dev/data/media
mount -o ro /dev/data/media-snap /mnt/snap
# ... back up /mnt/snap ...
umount /mnt/snap
lvremove /dev/data/media-snap

The snapshot size is the COW buffer — make it large enough to hold all writes during the snapshot's lifetime. If it fills, the snapshot is invalidated.

Thin provisioning

For modern setups, thin pools let you over-commit. You create a thin pool and then thin LVs that only consume the space they actually use:

lvcreate -L 500G -T data/thin-pool
lvcreate -V 100G -T data/thin-pool -n db1
lvcreate -V 100G -T data/thin-pool -n db2
# both LVs see 100G; the pool tracks real usage

When LVM goes wrong

A missing PV after a disk failure shows as a VG with FAILED status. vgreduce --removemissing drops the dead PV, but any LV that had extents on it is corrupt. Plan for failure: mirror critical VGs with lvconvert -m1, or use LVM on top of RAID.

Related