Create a Custom Linux Setup for WSL2

I just came across the amazing Windows Subsystem for Linux 2 (WSL2) feature which allows you to create a consistent Linux environment.

If you have not came across WSL2 yet, Microsoft advertises it as:

The Windows Subsystem for Linux lets developers run a GNU/Linux environment – including most command-line tools, utilities, and applications – directly on Windows, unmodified, without the overhead of a traditional virtual machine or dualboot setup.

Although, Microsoft provides some Linux distributions through its Windows Store, this leaves the question open what you should do if your favorite distro is not available over this channel, and how to achieve a consistent setup.

The great news is that you can import an exported Container image in WSL2 as your own distro. Microsoft’s documentation Import any Linux distribution to use with WSL shows this with vanilla CentOS 8. But let’s take this a little bit further and add customizations.

We are going to use CentOS Stream 8 as our base distribution. Then we install some additional tooling including zsh and oh my zsh. And of course we do this in a single Dockerfile.

 4RUN dnf update -y \
 5        && \
 6    dnf install -y \
 7        epel-release \
 8        && \
 9    dnf install -y \
10        git \
11        man \
12        passwd \
13        powerline-fonts \
14        sudo \
15        util-linux-user \
16        zsh \
17        && \
18    dnf clean all -y \
19        && \
20    adduser -G wheel ${USERNAME} && \
21        echo -e "[user]\ndefault=${USERNAME}" >> /etc/wsl.conf && \
22        echo ${PASSWORD} | passwd --stdin ${USERNAME}
24RUN curl -fsSL | sh - 
  1. We build this with: docker build -t wsl-centos:stream8 --build-arg USERNAME=veit --build-arg PASSWORD=password .

  2. Now we need a container instance which we can export afterwards: Create a container instance: docker run -t wsl-centos:stream8 bash ls /

  3. List all container instances docker ps -a.

    Terminal with a list of container images.

  4. Copy the container ID to the clipboard.

  5. Export the container to a tar file: docker export --output="centos-stream8.tar" [CONTAINER_ID]. Paste the container ID from the previous step into this command.

Now let’s configure the WSL2 environment on Windows:

  1. Windows needs a storage location for your running WSL. The storage location should be fast and have enough space for the VM which will be created. I will put this in my home directory: md C:\Users\veit\wsldistrostorage\centos-stream8

  2. We can import the tar file into WSL: wsl --import [DISTRO NAME] [STORAGE LOCATION] [FILE NAME].. e.g. wsl --import CentOS-Stream8 C:\Users\veit\wsldistrostorage\centos-stream8 centos-stream8.tar

  3. Finally, lets start the new WSL distro: wsl -d CentOS-Stream8

Of course this works with any Linux distribution for which you can find a Docker base image. And the nice part is, that you can create a repeatable setup with the Dockerfile.