Easily making a blockdev available to a container
5 March, 2021 by
Easily making a blockdev available to a container
| No comments yet

Often it would be nice to mount an existing (lvm) block device into a container. For instance, to emulate an Amazon ec2 environment, I’d like to have /dev/vdb or /dev/xvdb as a block device.

So I wrote a mount hook which will ‘insert’ a block device from the host into the container. Of course in Ubuntu containers are clamped down so that the container isn’t allowed to use this device. So I use this script to set a container up to use a particular block device.

For instance, if I have a pristine lvm-backed container called ‘quantal-amd64’, and I want to run a container which has a 500M block device available as /dev/xvdb, I would do:

# clone a new container
sudo lxc-clone -s -o quantal-amd64 -n q1
# create a LVM block device in the lxc VG
sudo lvcreate -L 500M -n q1-d1 lxc
# expose the block device to the container as /dev/xvdb
sudo lxc-enabledev.sh name_of_the_container /dev/lxc/q1-d1 xvdb

Now when I start the container, I can format the device and mount it:

sudo mkfs.ext2 /dev/xvdb
sudo mount /dev/xvdb /mnt
echo "hello world" | sudo tee /mnt/ab

Of course I can also format the device on the host, and preserve the device between multiple containers.

If this turns out to be something many people want, we can add support for this into lxc itself. But for the moment this meets my needs, and uses only existing lxc features.

One note: when you delete the container, you’ll want to also delete the custom apparmor profile which this created.

Note : You can use the “lxc-device” command to pass devices into containers.

Sign in to leave a comment