KVM Support inside LXC Containers

Today, I had to add support for running KVM virtual machines inside an LXC container. More as a reminder to myself, in case I ever have to do this again, here the simple recipe:

LXC Container Config Adjustment

Enable lxc.autodev and execute hook script to be executed after initial /dev creation:

[...]

# Auto-create /dev nodes and add native KVM support to the LXC container
lxc.autodev = 1
lxc.hook.autodev = /var/lib/lxc/.hooks/lxc-hook.kvm-support
lxc.cgroup.devices.allow = c 10:232 rwm
lxc.cgroup.devices.allow = c 10:238 rwm
lxc.cgroup.devices.allow = c 10:241 rwm

[...]

LXC Hook Script for KVM Support Enablement

The following script I placed at /var/lib/lxc/.hooks/lxc-hook.kvm-support (on the LXC host!):

#!/bin/sh

# set up native KVM support in LXC container
mknod -m 0660 ${LXC_ROOTFS_MOUNT}/dev/kvm c 10 232
chown :kvm ${LXC_ROOTFS_MOUNT}/dev/kvm
mknod -m 0660 ${LXC_ROOTFS_MOUNT}/dev/vhost-net c 10 238
chown :kvm ${LXC_ROOTFS_MOUNT}/dev/vhost-net
mknod -m 0660 ${LXC_ROOTFS_MOUNT}/dev/vhost-vsock c 10 241
chown :kvm ${LXC_ROOTFS_MOUNT}/dev/vhost-vsock