Working with LXC

Updated 21 August 2019

Instant backups

If using Btrfs, zfs or lvm, lxc-snapshot can be executed almost instantly. It may be essential when you need to eliminate or minimize service downtime. If you use Btrfs on your container, you should use the -B btrfs parameter when running lxc-create. Then lxc will create a subvolume to store the contents of the rootfs container. Later on, the container will be cloned using Btrfs own tools.

If you already have a container and running on the Btrfs filesystem, you can convert it. To do this, follow the steps below. For a different file system, you will also have to transfer the data to a different media, format the first one, move the data back and then do the following.

Migration

In this example, the container name is calculate. Replace it with yours.

Stop the container:

/etc/init.d/lxc.calculate stop

Rename the rootfs directory:

cd /var/calculate/lxc/calculate

mv rootfs rootfs.old

Create a Btrfs subvolume and move the contents of rootfs to it:

btrfs subvolume create rootfs

mv rootfs.old/* rootfs/

rmdir rootfs.old

Adjust the settings, namely by replacing dir with btrfs:

/var/calculate/lxc/calculate/config

...
lxc.rootfs.path = btrfs:/var/calculate/lxc/calculate/rootfs
...

Start the container:

/etc/init.d/lxc.calculate start

Checking up

To make sure that the container is now located on the Btrfs subvolume, run:

btrfs subvolume list /var/calculate

ID 274 gen 258 top level 5 path lxc/calculate/rootfs

Create a snapshot of the container:

time /etc/init.d/lxc.calculate stop

real    0m2.252s

time lxc-snapshot calculate

real    0m0.072s

time /etc/init.d/lxc.calculate start

real    0m1.186s

As you can see, it takes just over 3 seconds to backup. Once performed, a subvolume will be created, containing a copy of the data:

btrfs subvolume list /var/calculate

ID 274 gen 258 top level 5 path lxc/calculate/rootfs
ID 277 gen 32 top level 5 path lxc/calculate/snaps/snap0/rootfs

Conclusions

In addition to faster snapshots, you will also use less disk space, as the data will only be written to your hard drive as changes in files become too many. However, we recommend that you save a copy of your snapshot (snap0) to another location, or better yet, to another server. You can, for example, use Rsnapshot to do this.