Mounting a WSL2 disk image under Linux
[ linux , wsl2 ]

I’ve recently switched from Windows to Manjaro Linux. I used WSL2 a lot before switching (or more accurately, WSL2 was the reason I switched), and sometimes I need files from the WSL2 disk image while I’m in Linux. After a bit of googling, I found that I can easily mount the disk image and work with it as if it were any other drive.

Finding the disk image

The first thing you need to do is to find the disk image used by the WSL2 virtual machine. If your NTFS partition is mounted read-only, you also need to copy the disk image to your Linux partition. The disk image is located here:

/Users/<YourUserName>/AppData/Local/Packages/<PackageName>/LocalState/ext4.vhdx

In my case, the package name is:

CanonicalGroupLimited.Ubuntu20.04onWindows_79rhkp1fndgsc

Mounting the disk image

First I tried using libguestfs to mount the image but it didn’t work on Manjaro because of a bug which has already been fixed but the fix hasn’t been released yet (and I didn’t want to compile from source). Fortunately it can be done in another way.

The tools we will use are qemu and nbd-client. On Manjaro and Arch, you will need the qemu-headless (or qemu) and nbd packages:

# pacman -S qemu-headless nbd

On Debian or Ubuntu, you need the following:

# apt install qemu-utils nbd-client

Then remove the nbd kernel module if it is loaded (if it isn’t, this command will return an error you can safely ignore) and load it again with partition support:

# rmmod nbd
# modprobe nbd max_part=16

Ater that, make the disk image available using the NBD protocol with qemu-nbd:

# qemu-nbd -c /dev/nbd0 /path/to/ext4.vhdx

Then create a new mount point for the disk and mount it:

# mkdir /mnt/wsl2
# mount -o rw,nouser /dev/nbd0 /mnt/wsl2

Unmounting the disk image

When you no longer need the disk image, you can unmount it and unload the kernel module with the following commands:

# umount /mnt/wsl2 && qemu-nbd -d /dev/nbd0 && rmmod nbd