Backing File and Snapshot in QEMU/KVM

In any Virtual Machine application, there is nothing better than creating a Snapshot. It assist us save the current machine state. And, any further changes to the disk of virtual machines will also be saved. This makes it easy to revert the original state at any time. QEMU/KVM implements it by using backing file. Backing file is paired with snapshot disk image of virtual machine. Thereafter, QEMU/KVM uses original disk image as read only image. And, any writes to the disk image are redirected to snapshot file as Redirect-on-Write. This allows reads from backing file and writes to snapshot file. Snapshot file is a QCOW2 disk image, therefore it only registers writes on the disk.

However, backing file is also effective in allowing multiple virtual machines to run backed. This can be done through single disk image as base image, where base image is immutable in nature.

Backing File and Snapshot in QEMU/KVM

Lets go through the process of implementation, first to get information about the clean base image, we can use

qemu-img info clean-disk.qcow2

It displays information such as file format type, name, virtual size, disk size, cluster size.

To create clean-disk.qcow2 as backing image for snapshot.qcow2

qemu-img create -f qcow2 -b clean-disk.qcow2 snapshot.qcow2

In order to check the image file, run

qemu-img info snapshot.qcow2

This should display the clean-disk.qcow2 image as backing file for snapshot.qcow2, now use snapshot.qcow2 image as host disk image. Snapshot image backs up all the changes made.

To revert to original state of the machine, simply delete the backing file, which in this case is snapshot.qcow2 and also point the disk image to original image.

Save changes of snapshot to the original disk image

Now in case you want to save changes of snapshot to the original disk image and continue using the image further, then follow below mentioned steps :

Make back-up of original clean disk image

cp clean-disk.qcow2 new-clean-disk.qcow2

then rebase snapshot to use new disk image

qemu-img rebase -b new-clean-disk.qcow2 snapshot.qcow2

then commit changes of snapshot by

qemu-img commit snapshot.qcow2

This will store snapshot to original image with changes. Now, we can use a new-clean-disk.qcow2 as standalone image file with changes. Whereas, discard snapshot.qcow2 if required.