Using kvm/qemu in WSL2

Learn how to setup kvm/qemu and manage guest VMs with virsh.

Configure WSL

Add the below to /etc/wsl.conf.

[wsl2]
kernelCommandLine = "cgroup_no_v1=all systemd.unified_cgroup_hierarchy=1"
nestedVirtualization = true

[boot]
systemd = true
command = /bin/bash -ec "chown -v root:kvm /dev/kvm && chmod 660 /dev/kvm"

If cgroup is causing problems, fix them via /etc/fstab.

cgroup2 /sys/fs/cgroup cgroup2 rw,nosuid,nodev,noexec,relatime,nsdelegate 0 0

Setup the libvirt deamon

Install required packages to run qemu via virsh.

apt install --no-install-recommends \
  qemu-system libvirt-clients libvirt-daemon-system \
  dnsmasq virtinst

Optionally, set the default connect uri. Add this to something like ~/.bash_profile, in order to persist it.

export LIBVIRT_DEFAULT_URI='qemu:///system'

Allow the current user to use libvirt.

sudo usermod --append --groups kvm,libvirt '<user>'

Now, WSL needs to restart in order to pick up the changes and start the libvirt deamon. This can be done via powershell.

wsl.exe --shutdown

Verify the installation

Check if the service is running ok. It is expected to show an error, regarding dmi. This can be safely ignored.

systemctl status libvirtd

At this point, we should be able to run virsh commands.

virsh nodeinfo
virsh list --all

Create a guest VM

First check which os variants are supported. For example, looking for alpine.

virt-install --osinfo list | grep alpine

Use some supported version.

curl -fsSLO https://dl-cdn.alpinelinux.org/alpine/v3.17/releases/x86_64/alpine-virt-3.17.7-x86_64.iso

Then install the guest VM.

virt-install \
  --name alpine-amd64 \
  --virt-type kvm \
  --cdrom alpine-virt-3.17.7-x86_64.iso \
  --os-variant alpinelinux3.17 \
  --disk size=10 \
  --memory 1024

Helpful Resources