WSL2 (Ubuntu-20.04)にDockerをインストール

f:id:tworks55:20220227132632p:plain

Docker desktopをインストールしなくてもWSL2でDockerが使えるようなので試してみました。バグなどを踏まなければ非常に簡単です。

使った環境はUbuntu-20.04です。

PowerShell 7.2.1
Copyright (c) Microsoft Corporation.

https://aka.ms/powershell
Type 'help' to get help.

PS C:\Users\tworks55> wsl -l -v
  NAME            STATE           VERSION
* Ubuntu-20.04    Running         2
  Ubuntu          Stopped         2
PS C:\Users\tworks55>

Install Docker Engine on Ubuntuに手順が記載されているのでこの通りに実行します。

1. HTTPS経由でaptコマンドがリポジトリを使えるように必要なパッケージをインストールします。
> sudo apt-get update

> sudo apt-get install \
    ca-certificates \
    curl \
    gnupg \
    lsb-release
2. Dockerのofficial GPG keyを追加します。
> curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
3. 安定版のリポジトリが使えるように設定します。
> echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
4. Docker Engineをインストールします。
> sudo apt-get update

> sudo apt-get install docker-ce docker-ce-cli containerd.io
5. Docker serviceを起動します。

WLS2のUbuntu20.02ではインストール直後はサービスは起動しないようです。

ステータスを確認すると dockerの箇所が[ - ] になっています。

tworks55@LAPTOP-A1R0H57F:~$ service --status-all
 [ - ]  apparmor
<中略>
 [ - ]  docker

ということで、サービスを起動します。

> sudo service docker start

dockerの箇所が[ + ]になりました。

tworks55@LAPTOP-A1R0H57F:~$ service --status-all
 [ - ]  apparmor
<中略>
 [ + ]  docker
6. Hello worldでDockerが使えるか試します。
tworks55@LAPTOP-A1R0H57F:~$ sudo docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
2db29710123e: Pull complete
Digest: sha256:97a379f4f88575512824f3b352bc03cd75e239179eea0fecc38e597b2209f49a
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

以上でWSL2 (Ubuntu-20.04)にDockerをインストールすることができました。

これでDocker desktopはもう使わなくても良いかな。