Mounting another disk as ext4 in WSL2

Here we learn how to create a virtual disk meant to be mounted in WSL.

Introduction

On my development machine, I run various WSL (now WSL2) instances. I needed to have a common disk that would store all the code and can be mounted on the different instances.

While this could’ve been done by regular folders as well, the performance of the NT file system is abysmal when it comes to a large number of tiny files (node_modules anyone?). This meant that that this common disk had to be an ext4 disk.

Outline

  • Windows: Create a file.
  • WSL: Format the file as ext4.
  • WSL: Mount the file as a disk.

Steps

Create a file

A dummy file can be created on windows using fsutil.

fsutil file createNew <call-this-file-whatever-you-want> <size-in-bytes>

For this example, the file we’ll use will be called development.ext4 with a size of 16GB

fsutil file createNew development.ext4 17179869184

Format the file as ext4

Now, this (empty) file needs to be formatted as ext4. In WSL, this can be done by the following command:

mkfs.ext4 -b 1024 <location-for-development.ext4>

This formats the empty file as a virtual disk with an ext4 file system with a block size of 1024.

(Optional) Remove reserved blocks:

tune2fs -m 0 <location-for-development.ext4>

(Optional) Increase throughput:

tune2fs -o journal_data_writeback <location-for-development.ext4>

Mount the file as a disk

Now, the file simply needs to be mounted inside WSL as a disk. This can be done using the following command:

sudo mount -t ext4 <location-for-development.ext4> <mount-point>

For me, the mount point was /projects, hence the command above becomes

sudo mount -t ext4 <location-for-development.ext4> /projects

With this, the file will be mounted at /projects, and now can be treated as a regular file/disk.

Conclusion

This works for me. However, I can’t get this to automount via fstab due to limitations with WSL. For the time being, I’ve created an entry in /etc/fstab in WSL, and mounting it using the windows task scheduler using:

sudo mount --all

Now, when I need to back up my projects, backing up a single file (development.ext4) is going to be a lot simpler than backing up multiple individual files (a VCS is a better fit for that anyway)

Hope this helps someone, cheers!