Mastering LVM Snapshots: Create, Restore, Merge and Test Environments
This guide explains the LVM snapshot mechanism, demonstrates how to create snapshots, restore individual files or entire volumes, merge snapshots back into the original LV, and use snapshots to build disposable test environments on Ubuntu systems.
LVM Snapshot Principle
LVM provides snapshot functionality that allows you to back up a filesystem without stopping services. Snapshots use Copy‑On‑Write (COW) technology, creating hard‑links to the original data blocks; only changed blocks are copied to the snapshot area.
The snapshot resides in the same volume group (VG) as the original logical volume (LV) and requires reserved space within the VG.
Create LVM Snapshot
First check the current LV and VG status. In the example,
nicklv00(15 GB) resides in
nickvg(70 GB total, 55 GB free). Create a snapshot with the same command used for LV creation:
<code>$ sudo lvcreate -L 15G --snapshot --name nicksnap00 nickvg/nicklv00</code>The snapshot appears as a special LV that initially shares all data blocks with the source LV.
Restore Partial Data
Mount the snapshot LV, locate the old version of a file (e.g.,
/home/doc/hello.txt), and copy it back to the original location using
cp.
<code># mount /dev/mapper/nickvg-nicksnap00 /mnt/snap
# cp /mnt/snap/home/doc/hello.txt /home/doc/hello.txt</code>Restore Whole Volume
When many files need restoration, export the snapshot contents to a temporary location, then extract them back to the original LV after reformatting.
<code># mkdir /home/nick/backup
# tar -czf /home/nick/backup/lvm.tar.gz -C /mnt/snap .
# umount /dev/mapper/nickvg-nicklv00
# mkfs.ext4 /dev/nickvg/nicklv00
# mount /dev/mapper/nickvg-nicklv00 /home/doc
# tar -xf /home/nick/backup/lvm.tar.gz -C /home/doc</code>Merge Snapshot
Instead of the manual export/import process, you can merge the snapshot back into the original LV using
lvconvert --merge. Unmount the source LV first, then run:
<code>$ sudo lvconvert --merge nickvg/nicksnap00</code>The merge automatically removes the snapshot LV.
Use Snapshot for Test Environment
Create a snapshot, mount it as a separate test volume, perform any modifications, and when testing is complete, simply unmount and delete the snapshot. Repeat as needed for new test cycles.
Conclusion
Snapshots are an advanced yet practical feature of LVM. The methods described—creating snapshots, restoring data, merging, and leveraging snapshots for testing—cover the essential use cases for everyday system administration.
Raymond Ops
Linux ops automation, cloud-native, Kubernetes, SRE, DevOps, Python, Golang and related tech discussions.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.