Backup and Restore KVM Vms

Sylia CHIBOUB
2 min readJan 8, 2021

--

Photos via Pexels

Introduction

KVM stands for Kernel based Virtual Machine and according to Redhat, it is an open source virtualization technology built into Linux. Specifically, KVM lets you turn Linux into a hypervisor that allows a host machine to run multiple, isolated virtual environments called guests or virtual machines (VMs).

In today’s article, i will mainly cover the topic of KVM VMs backup.

Backup your KVM VM

First, Login as sudo and list all of your available KVM virtual machines.

sudo su
virsh list --all

Next, you need to shutdown the VM you want to backup.

virsh shutdown vm_name

Then run the following to verify that the above command worked well.

virsh list --all

Backing up a KVM virtual machine mainly consists of two parts:

  • The domain definition:

The definition of the hardware of the VM including the network devices, configuration and virtual CPUs, disk and memory etc. You can view this through using the following command:

virsh dumpxml vm_name
  • The data file

The source file path contains the path to our data file that we need to backup. It stores the hard drive of the VM. This is where the internal configuration is such as services, databases etc. In order to find the location of this file we can use the domain definition or we can use the following command which will give you the location of the hardrive.

virsh domblklist vm_name

Let’s suppose that the given location is:

/var/lib/libvirt/images/

In order to backup the domain definition, we run the following:

virsh dumpxml vm_name > /opt/kvm_backup/vm_name.xml

In order to backup the hard drive, we use the following

cp /var/lib/libvirt/images/xxxx.qcow2 /opt/kvm_backup

So, in the/opt/backup folder, we’ll find the domain definition and the hard drive of the VM.

To check the size of the hardrive : du -hs xxxx.qcow2

Restore your KVM VM

First, we’ll start by undefining the VM and deleting its hardrive so that it doesn’t exist anymore.

  • Undefine the VM:
virsh undefine vm_name
virsh list --all
  • Delete the harddrive
cd /var/lib/libvirt/images
rm -rf xxxx.qcow2
  • Restore the VM

Now, in order to restore the deleted VM, we first restore the hard drive:

cp /opt/kvm_backup/wxxx.qcow2 /var/lib/libvirt/images/

Then, restore the domain definition

virsh define --file  /opt/kvm_backup/vm_name.xml

You can then checkout that the informations inside vm_name.xml are correct if you’re putting it on a different physical host. For example verify that the network interfaces exist on the new physical host etc.

Finall, run the following to verify that your VM have been correctly defined:

virsh list --all

Then, start the VM:

virsh start vm_name

Once your VM is running, SSH into it to verify that everything have been restored correctly.

References

--

--

Sylia CHIBOUB
Sylia CHIBOUB

Written by Sylia CHIBOUB

Supporting Open Source and Cloud Native as a DevOps Engineer