Use Docker in WSL2
Posted Jun 27, 2020 • 2 min read
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
- unshare:Run the command in the new namespace. man page
- nsenter:Run commands in a namespace. man page
- runuser:Switch the user who executes the command. man page
Our steps are
pidofto check if there is a
systemdprocess. If yes, skip to 3, otherwise 2.
systemdso that the PID of
systemdin the new namespace is 1. The entire command is executed with the
daemonizecommand, and the systemd created in this way runs continuously as a background process.
runuserto 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