Use Docker in WSL2

Posted Jun 27, 20202 min read

Original link

WSL2 is a Linux based on Hyper-V virtualization, so I want to run Docker in WSL. When I happily installed Docker, I found that it could not be started, because the process with PID 1 was not systemd, but init, which made me a chicken. After some searching, I found that someone gave a solution on GitHub, Genie , the principle is to use Linux namespace to achieve isolation, and run systemd in the isolated space. In this way, the PID of systemd is 1.

After reading the code, I get a few key commands

  1. unshare:Run the command in the new namespace. man page
  2. nsenter:Run commands in a namespace. man page
  3. runuser:Switch the user who executes the command. man page

Our steps are

  1. Use pidof to check if there is a systemd process. If yes, skip to 3, otherwise 2.
  2. Let unshare run systemd so that the PID of systemd in the new namespace is 1. The entire command is executed with the daemonize command, and the systemd created in this way runs continuously as a background process.
  3. Use nsenter and runuser to enter the newly created namespace and run the shell as a user.

So we can get such a script, GitHub Portal

#!/bin/bash

systemd_pid=
if [z-$(pidofsystemd)]; then
    daemonize/usr/bin/unshare -fp--propagation shared--mount-proc systemd
fi

while [-z $systemd_pid]
do
    for pid in $(pidofsystemd)
    do
        systemd_pid=$pid
    done
done

if [-z $WHO]; then
    WHO=root
    WD=/
else
    WD=/home/$WHO
fi

nsenter-t $systemd_pid -m -p--wd=$WD runuser-m -p -u $WHO zsh

Instructions:

WHO=`whoami` sudo-E./wslsystemd.sh