# Logical Volume Management (LVM)

> Chapter 13 of the Courseiva LINUX-PLUS curriculum — https://courseiva.com/learn/linux-plus/logical-volume-management

**Official objective:** 4.2 — Configure and manage Logical Volume Manager (LVM)

## Introduction

Exam objective 4.2 asks you to configure and manage Logical Volume Manager (LVM). This concept solves a fundamental pain point: running out of disk space on a single partition, which used to mean hours of downtime or risky manual repartitioning. LVM gives you the superpower of adding, removing, or resizing storage space while the system is still running, making it a critical skill for any Linux administrator.

## The Apartment Block Renovation Analogy

A physical apartment block is a single building with fixed walls and rooms. 

Now imagine you are the building manager of a block where every room has a fixed size. The tenants in Apartment 1 have lots of empty space they never use, while the tenants in Apartment 2 are tripping over furniture because it is too small. You cannot move that unused space from Apartment 1 into Apartment 2 because the walls are solid. To give Apartment 2 more room, you would have to knock down walls, get new permits, and possibly move people out. That is disruptive and expensive. 

Logical Volume Management (LVM) is like converting the entire building into a flexible, modular system. Instead of fixed apartments, you have a giant open warehouse of construction materials. This warehouse is your Volume Group (VG). The materials are Physical Volumes (PVs) — individual bricks, planks, and sheets of drywall. To create an apartment, you take some of those materials and build a room. This room is a Logical Volume (LV). If Apartment 2 needs more space, you do not move walls. You simply walk to the warehouse, pick up more materials, and extend the room. The tenants never have to move out, and you do not need building permits. 

Furthermore, if one of the physical bricks (a hard drive) starts to fail, LVM lets you save the day without knocking anything down. You can copy the materials from that failing brick onto healthy ones, all while the tenants are still living inside. This is called a live migration. The apartment block stays open and functional while the maintenance happens behind the scenes. This flexibility to expand, shrink, and move space without downtime is exactly what LVM provides for computer storage.

## Core explanation

To understand LVM, you first need to know how traditional storage works. A hard drive (like a 1TB SSD) is split into partitions. A partition is a fixed chunk of the drive, like a slice of a pie. Once you create a partition and put a file system on it (like ext4 or xfs), its size is locked. If the partition gets full, you have to back up all your data, repartition the drive, restore the data, and hope the system boots again. This is painful, time-consuming, and risky. 

LVM totally changes this. Instead of working with fixed partitions, you stack three layers: Physical Volumes (PVs), Volume Groups (VGs), and Logical Volumes (LVs). 

- Physical Volume (PV): This is a hard drive, or a partition on a hard drive, that LVM can use. You mark a drive as a PV by running a command like `pvcreate`. Once it is a PV, the drive is no longer a simple block of space. LVM divides it into small equal-sized chunks called Physical Extents (PEs). A PE is usually 4MB in size by default. Think of PEs as tiny bricks that LVM can mix and match. 

- Volume Group (VG): You combine one or more PVs into a single pool of storage. This pool is the VG. The VG does not care about the physical boundaries of the drives. You could have three drives of 500GB, 1TB, and 2TB, and combine them all into one VG of 3.5TB total space. That space is now a flexible resource. 

- Logical Volume (LV): From the VG, you carve out chunks of space to create LVs. These are what the operating system sees and uses. You format an LV with a file system (like ext4) and mount it to a folder (like `/home`). The big difference is that you can resize an LV without repartitioning. If `/home` is getting full, you can tell LVM to add more space to that LV from the free space in the VG. This process can be done while the volume is mounted and in use. 

LVM also provides features like snapshots. A snapshot is a point-in-time copy of an LV. It uses a clever technique: it does not copy all the data immediately. Instead, it tracks which blocks change after the snapshot is taken, and saves only the original data of those changed blocks. This makes snapshots very fast to create and requires little space at first. If you need to revert to a previous state, LVM can roll back the main LV to the snapshot. 

Another feature is striping. Instead of storing data sequentially on one drive, LVM can spread data across multiple PVs in a stripe pattern. This looks like RAID 0. Striping improves performance because multiple drives are reading and writing at the same time. However, it also increases the risk of data loss if one drive fails. 

LVM also supports mirroring, which writes identical copies of data to two PVs. This is like RAID 1. If one hard drive dies, the other copy is there instantly. The system keeps running without a hiccup. You can even perform live migration of data. If you need to replace a failing hard drive that is part of a VG, you can tell LVM to move all its PEs to another healthy PV while the system is online. 

To manage all of this, you use command-line tools. `pvcreate`, `pvdisplay`, `pvs` for physical volumes. `vgcreate`, `vgdisplay`, `vgs` for volume groups. `lvcreate`, `lvdisplay`, `lvs` for logical volumes. `lvextend`, `lvreduce`, `lvresize` for changing sizes. `lvremove` for deleting. And the crucial step after resizing an LV: you must also tell the file system to resize itself. For ext4, you run `resize2fs`. For xfs, you run `xfs_growfs`. If you forget this step, the system will think the LV is bigger, but the file system will not use the extra space. 

LVM replaced the old nightmare of static partitions. It gives you on-the-fly flexibility, protects you from downtime, and scales across multiple drives seamlessly. Once you use LVM, going back to fixed partitions feels like using a hammer when you have a power drill.

## Real-world context

Let us walk through a real scenario faced by an IT professional at a mid-sized company. The company runs a web application with a MySQL database that stores customer orders. The database sits on a Linux server that was set up years ago with a single 500GB hard drive. The data is stored in a traditional partition mounted at `/var/lib/mysql`. The partition is at 85% capacity and growing every day. The company expects the next six months of sales to fill the drive completely. 

The professional, let us call her Ana, has two goals. First, avoid any downtime — the database must stay online because customers place orders 24/7. Second, make future upgrades painless. If she simply adds another hard drive and mounts it somewhere else, the database would not automatically use it. The database expects its files in `/var/lib/mysql`. 

Ana decides to migrate the database to LVM. She has three drives available in the server: the original 500GB drive (now full), a new 1TB SSD, and a spare 200GB HDD. Here is the step-by-step plan: 

1. Prepare the physical volumes. Ana installs the new drives, then runs `pvcreate /dev/sdb` and `pvcreate /dev/sdc` to mark them as physical volumes. She also runs `pvcreate /dev/sda1` on the existing partition, after backing up the data and unmounting it overnight during a scheduled maintenance window. 

2. Create the volume group. She runs `vgcreate datavg /dev/sdb /dev/sdc /dev/sda1`. This creates a single pool called 'datavg' with total capacity of 1.7TB. 

3. Create the logical volume. She runs `lvcreate -n mysqlvol -L 1.5T datavg`. This carves out a 1.5TB logical volume named 'mysqlvol' from the pool. 

4. Format and mount. Ana formats `/dev/datavg/mysqlvol` with ext4 using `mkfs.ext4 /dev/datavg/mysqlvol`. Then she mounts it to `/var/lib/mysql` and restores the backed-up data. 

Now, a few months later, the company's sales surge, and the database outgrows 1.5TB. Ana checks the free space in the VG with `vgs` and sees she has 200GB free. She extends the LV with `lvextend -L +200G /dev/datavg/mysqlvol`. Then she runs `resize2fs /dev/datavg/mysqlvol` to grow the file system. The database does not even blink. No downtime, no backup and restore. 

Later, the spare 200GB HDD starts showing signs of failure. S.M.A.R.T. errors appear in the logs. Ana needs to remove it without powering down. She uses `pvmove /dev/sdc` which tells LVM to copy all the data from that failing drive to the healthy 1TB SSD. This happens live. Once the move completes, she runs `vgreduce datavg /dev/sdc` to remove the drive from the group, then replaces the drive physically next time she is in the data centre. 

Ana now also uses LVM snapshots to create quick backups before major software updates. Before applying a MySQL patch, she runs `lvcreate -s -n mysql_snap -L 50G /dev/datavg/mysqlvol`. This creates a writable snapshot. If the update breaks something, she can revert in minutes by merging the snapshot back. 

This scenario is not theoretical. Thousands of production servers use LVM exactly this way. It is the standard method for managing storage in enterprise Linux environments because it gives the administrator control and safety without downtime.

## Exam focus

The XK0-006 exam tests your ability to configure and manage LVM, as stated in objective 4.2. You can expect multiple-choice questions, fill-in-the-blank commands, and scenario-based questions where you must choose the correct sequence of commands. 

The exam loves to test the correct order of command types in an LVM setup. The required order is: PV, then VG, then LV. If a question asks you to set up LVM from scratch, they will expect you to pick the commands `pvcreate`, then `vgcreate`, then `lvcreate`. They will deliberately set traps by listing `lvcreate` first or by mixing up the layers. 

Trending topics that appear in every exam attempt: 
- The difference between Physical Extent (PE) and Logical Extent (LE). They are the same thing — a fixed-size chunk of storage. The exam expects you to know they are used for mapping and that the default size is 4MB. 
- The snapshot feature. You need to know that snapshots use 'copy-on-write' technology. They are fast to create and efficient in space early on. They are not full clones until the origin changes data. 
- Resizing operations. The exam will present a scenario where the logical volume is extended but the file system still shows the old size. The answer is that you must run a file system-specific resize command (`resize2fs` for ext4, `xfs_growfs` for xfs). A common trap is giving a command like `lvresize` and expecting that to be sufficient for the file system. 
- Volume group extension and reduction. Know that you cannot remove a PV from a VG if it has allocated extents. You must first use `pvmove` to relocate the data. 
- The difference between `lvextend` and `lvresize`. Both can increase size, but `lvresize` is a combined command that can also shrink. The exam tests whether you know that shrinking is risky and often requires specific steps. 
- Striping vs. mirroring. Know the trade-offs: striping improves performance but increases failure risk; mirroring protects against failure but halves the usable space. 

Key command names to memorise: 
- `pvcreate`, `pvdisplay`, `pvs`, `pvmove`, `pvremove` 
- `vgcreate`, `vgdisplay`, `vgs`, `vgextend`, `vgreduce`, `vgremove` 
- `lvcreate`, `lvdisplay`, `lvs`, `lvextend`, `lvreduce`, `lvresize`, `lvremove`, `lvchange` 

Exam trap patterns: 
- Swap space on LVM: You can create an LV for swap, but you must use `mkswap` and `swapon`. The exam expects you to know the correct command for formatting swap. 
- Mixing file system types with resize commands. They will offer `xfs_growfs` for an ext4 volume. You must match the file system with its tool. 
- Failing to unmount a volume before shrinking. LVM does not support shrinking a mounted volume. You must unmount it first. The exam will sometimes present a shrinking scenario where the correct next step is to unmount. 

Memorise the full syntax of creating a striped or mirrored LV: `lvcreate -L 10G -n mylv -i 2 -I 64 myvg` (striped across 2 PVs with stripe size 64KB). For mirroring: `lvcreate -L 10G -n mylv -m 1 myvg` (one mirror copy).

## Step by step

1. **Prepare the hard drives as Physical Volumes** — Use `pvcreate /dev/sdX` on each disk or partition you want to include in LVM. This writes LVM metadata to the device and divides it into Physical Extents (PEs), which are typically 4MB chunks. The device is now ready to be added to a Volume Group.
2. **Create the Volume Group** — Run `vgcreate myvg /dev/sda /dev/sdb` to combine one or more Physical Volumes into a single pool called 'myvg'. The Volume Group tracks all the Physical Extents from its member PVs and allows you to allocate them to Logical Volumes.
3. **Create the Logical Volume** — Use `lvcreate -L 10G -n mylv myvg` to carve out a 10GB Logical Volume named 'mylv' from the VG. The LV appears as a block device at `/dev/myvg/mylv` or `/dev/mapper/myvg-mylv`. This is the device you will format and mount.
4. **Format the Logical Volume with a file system** — Run `mkfs.ext4 /dev/myvg/mylv` to create an ext4 file system on the LV. Without this step, the volume has no structure and cannot hold files. The file system type must match the tools you will use later for resizing.
5. **Mount the Logical Volume** — Use `mount /dev/myvg/mylv /mnt/data` to attach the file system to a directory. The system can now read and write files. To make the mount permanent, add an entry to `/etc/fstab` using the device path or the UUID.
6. **Extend the Logical Volume when more space is needed** — First check free space with `vgs`. Then run `lvextend -L +5G /dev/myvg/mylv` to add 5GB. This makes the block device bigger. Finally, run `resize2fs /dev/myvg/mylv` to grow the file system into the new space. The volume remains mounted throughout.
7. **Replace a failing Physical Volume with live migration** — If a drive fails, add a new PV with `pvcreate /dev/sdc`, then add it to the VG with `vgextend myvg /dev/sdc`. Run `pvmove /dev/sdb` to copy all extents from the old failing drive to the new one. Then remove the old drive with `vgreduce myvg /dev/sdb`.

## Comparisons

### Physical Volume (PV) vs Logical Volume (LV)

**Physical Volume (PV):**
- A raw disk or partition that LVM has claimed.
- Divided into fixed-size Physical Extents (PEs).
- Represented as /dev/sda, /dev/sdb, etc.

**Logical Volume (LV):**
- A virtual block device carved from a Volume Group.
- Composed of Logical Extents (LEs) that map to PEs.
- Represented as /dev/myvg/mylv or /dev/mapper/myvg-mylv.

### Extending an LV (lvextend) vs Resizing the file system (resize2fs)

**Extending an LV (lvextend):**
- Expands the block device size.
- Can be done while the volume is mounted.
- Does not affect data structures directly.

**Resizing the file system (resize2fs):**
- Expands the file system to fill the block device.
- Must be run after lvextend for the space to be usable.
- Requires the correct file system-specific command.

### LVM Striping vs LVM Mirroring

**LVM Striping:**
- Spreads data across multiple PVs for faster read/write.
- No redundancy; one drive failure causes data loss.
- Created with `-i 2 -I 64` flags in lvcreate.

**LVM Mirroring:**
- Writes identical data to two PVs for fault tolerance.
- Uses twice the storage for the same data (usable space halved).
- Created with `-m 1` flag in lvcreate.

## Diagram

_Diagram showing how multiple Physical Volumes combine into one Volume Group, which then allocates space to Logical Volumes, which are formatted and mounted._

```mermaid
flowchart TD
    PV1[Physical Volume: /dev/sda] -->|combined into| VG[Volume Group: datavg]
    PV2[Physical Volume: /dev/sdb] -->|combined into| VG
    PV3[Physical Volume: /dev/sdc] -->|combined into| VG
    VG -->|allocate| LV1[Logical Volume: mysqlvol]
    VG -->|allocate| LV2[Logical Volume: backupvol]
    LV1 -->|formatted with| FS1[File System: ext4]
    LV2 -->|formatted with| FS2[File System: xfs]
    FS1 -->|mounted at| M1[Mount point: /var/lib/mysql]
    FS2 -->|mounted at| M2[Mount point: /mnt/backup]
```

## Common misconceptions

- **Misconception:** If I extend the logical volume, the file system automatically uses the new space. **Reality:** No. Extending the LV only gives the block device more space. The file system on top of it must be resized separately using `resize2fs` for ext4 or `xfs_growfs` for XFS. (LVM operates at the block level, but the file system manages data structures. The file system does not know the block device has grown until you specifically tell it to re-read the size.)
- **Misconception:** Snapshots take a full copy of the data at creation time. **Reality:** Snapshots use copy-on-write. They only track changes made after the snapshot was taken. The original data stays on the origin volume until overwritten. This makes snapshots fast to create and small initially. (The term 'snapshot' sounds like a photograph, which implies a complete copy. People assume it duplicates all data, similar to a backup. The technical reality is more efficient.)
- **Misconception:** You can shrink an LVM logical volume while it is mounted and in use. **Reality:** Shrinking an LV is very risky and normally requires the volume to be unmounted first. Most file systems (like ext4) must be offline to shrink safely. XFS does not support shrinking at all. (Since expanding an LV can be done online, beginners assume the reverse is also possible. But shrinking can cause data corruption if the file system is actively writing at the same time.)
- **Misconception:** A Volume Group can only use one physical hard drive. **Reality:** A Volume Group can combine multiple Physical Volumes from different hard drives into one pool. This is one of LVM's main advantages—it aggregates storage across drives. (The word 'group' might be misinterpreted as a grouping of partitions on one disk, but it is actually a grouping of disks or partitions from across the system.)
- **Misconception:** LVM makes the system faster by default. **Reality:** LVM adds a layer of abstraction, which can introduce a very slight overhead. It is not a performance enhancement. Only striping (like RAID 0) can improve speed, but that is a specific configuration choice. (People hear about 'flexibility' and 'advanced management' and assume it also boosts performance. In reality, the main benefits are flexibility and manageability, not raw speed.)

## Key takeaways

- LVM separates physical storage from logical storage using three layers: Physical Volumes, Volume Groups, and Logical Volumes.
- You must create a Physical Volume before you can add it to a Volume Group, and you must create a Volume Group before you can carve a Logical Volume from it.
- Extending a Logical Volume requires two steps: run `lvextend` on the LV, then resize the file system with `resize2fs` (ext4) or `xfs_growfs` (XFS).
- A snapshot uses copy-on-write technology: it takes almost no space at creation and only stores data that is about to be changed on the original volume.
- You can migrate data from a failing drive to a healthy one while the system is running using `pvmove`, then remove the faulty drive from the Volume Group.
- LVM supports striping for performance (like RAID 0) and mirroring for redundancy (like RAID 1); these are configured at Logical Volume creation time.
- A Volume Group can combine multiple physical drives of different sizes into one single pool of storage that Logical Volumes draw from.
- Snapshots are not backups—they depend on the original volume and cannot replace a full backup strategy.

## FAQ

**Why can I not see my LVM logical volume after rebooting?**

LVM volumes need to be activated by the system. Run `lvchange -ay /dev/myvg/mylv` to activate them, or ensure the LVM service (lvm2-lvmetad or lvm2-activation-generator) is enabled.

**Can I use LVM on my root (/) partition?**

Yes, most enterprise Linux distributions place the root filesystem on LVM by default. Booting from LVM requires a separate /boot partition (often on a non-LVM partition) so the bootloader can find the kernel.

**What happens if one drive in the Volume Group fails?**

If you have not used mirroring, any data stored on that failing drive is lost. LVM does not provide redundancy on its own. You must configure mirroring (like RAID 1) or use a separate RAID solution underneath LVM to protect against drive failure.

**How do I check how much free space is in my Volume Group?**

Use the `vgs` command to see a summary. For detailed information, use `vgdisplay myvg`. This shows total size, allocated size, and free extents.

**Can I shrink a Logical Volume without losing data?**

It is possible but risky and requires unmounting the volume first. You must shrink the file system (with `resize2fs` using the `-M` option for minimal size, or a specific size) before shrinking the LV with `lvreduce`. XFS file systems cannot be shrunk at all.

**Are LVM snapshots a good replacement for backups?**

No. Snapshots are useful for quick rollbacks during updates or testing, but they are tied to the original volume and can cause the system to crash if the snapshot runs out of space. Always use a separate backup strategy (like rsync, dump, or a backup tool) for disaster recovery.

## Check your understanding

1. **What is the correct order of commands to set up a new LVM volume from three unused hard drives?**

   Answer: First use `pvcreate` on each drive, then `vgcreate` to combine them into a Volume Group, then `lvcreate` to carve out a Logical Volume.

2. **You have extended an LVM Logical Volume with `lvextend -L +10G /dev/myvg/mylv`. The Linux system still shows the old size. What command do you need to run next?**

   Answer: If the file system is ext4, run `resize2fs /dev/myvg/mylv`. If it is XFS, run `xfs_growfs /mountpoint`.

3. **What is a Physical Extent (PE) and what is its default size?**

   Answer: A Physical Extent is the smallest unit of storage managed by LVM on a Physical Volume. Its default size is 4MB.

4. **You need to remove a failing hard drive from a Volume Group without rebooting. What two commands must you run?**

   Answer: Run `pvmove /dev/sdb` to migrate its data to another PV in the group, then run `vgreduce myvg /dev/sdb` to remove the drive from the Volume Group.

5. **What is the key difference between an LVM snapshot and a full backup?**

   Answer: A snapshot uses copy-on-write, only stores data that is about to be changed, and depends on the original volume. A full backup is an independent copy stored separately.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/linux-plus/logical-volume-management
