Master LVM Snapshots: Create, Restore, Merge and Test Environments on Ubuntu
This guide explains how LVM snapshots work using copy‑on‑write, shows step‑by‑step commands to create, mount, restore individual files or whole volumes, merge snapshots back into the original LV, and leverage snapshots for disposable test environments, all on Ubuntu 16.04.
LVM Snapshot Principle
LVM provides a snapshot feature that backs up a filesystem without stopping services. Snapshots use Copy‑On‑Write (COW) technology, creating hard links to the original data's inodes; unchanged data is shared, while modified blocks are copied to the snapshot area before being overwritten.
Snapshots are logical volumes that share physical extents (PE) with the original LV, requiring free space in the same volume group (VG) and must reside on the same VG as the source LV.
Creating LVM Snapshot
First, check the current volume sizes:
The data LV
nicklv00is 15 GB in VG
nickvg, which has 55 GB free, so there is enough space for a snapshot.
<code>sudo lvcreate -L 15G --snapshot --name nicksnap00 nickvg/nicklv00</code>The snapshot appears as a special LV; mounting it shows the same data as the original LV.
Restoring Partial Data
Mount the snapshot, locate the old version of the file, and copy it back:
Restoring the Entire Volume
Mount the snapshot and create a compressed archive of its contents:
After unmounting the source LV, format it, remount, and extract the archive:
<code>sudo umount /home/doc
sudo mkfs.ext4 /dev/nickvg/nicklv00
sudo mount /dev/mapper/nickvg-nicklv00 /home/doc
sudo tar -xf /home/nick/backup/lvm.tar.gz -C /home/doc</code>Merging Snapshot (lvconvert --merge)
Re‑create a snapshot, make changes, then unmount the source LV and merge the snapshot back:
<code>sudo lvcreate -L 15G --snapshot --name nicksnap00 nickvg/nicklv00
# modify files
sudo umount /home/doc
sudo lvconvert --merge nickvg/nicksnap00</code>The merge automatically removes the snapshot LV.
Using Snapshots to Create Test Environments
Create a snapshot, mount it as a separate test volume, perform any modifications, and delete the snapshot when testing is complete. This provides an isolated, disposable environment without affecting the production LV.
Summary
Snapshots are an advanced LVM feature, but the common use cases covered here—creating, restoring, merging, and using snapshots for testing—are sufficient for most daily system‑administration tasks.
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.