WSL2 UbuntuにDockerをインストール

WindowsにDockerDesktop入れたくないので実施

インストール

$ curl -fsSL https://get.docker.com -o get-docker.sh
$ ls -l ./get-docker.sh
$ sudo sh get-docker.sh

カレントユーザをdockerグループに所属させる

$ sudo usermod -aG docker $USER

systemd有効化確認

ls -l /etc/wls.conf

無ければ下記内容で/etc/wls.confを作成

[boot]
systemd=true

WSL停止

> wsl --shutdown

WSLアクセスしてDockerが起動していることを確認→active(running)であること

$ systemctl status docker

hello dockerを実行

$ docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
719385e32844: Pull complete
Digest: sha256:88ec0acaa3ec199d3b7eaf73588f4518c25f9d34f58ce9a0df68429c5af48e8d
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/

MongoDBを試す

docker run -itd -e MONGO_INITDB_ROOT_USERNAME=**** -e MONGO_INITDB_ROOT_PASSWORD=**** \
        -p 27017:27017 --name mongo mongo 

一応コマンドのメモ

  • docker run: Dockerコンテナを実行するコマンド
  • -itd: 3つのオプションの組み合わせ
    • -i: コンテナの標準入力を開いたままにし、コンテナがバックグラウンドで実行される場合でもコンテナにアタッチできるようにする
    • -t: 疑似TTY(テキスト端末)を提供し、コンテナ内のプロセスと対話できるようにする
    • -d: コンテナをデタッチドモードで実行し、コンテナがバックグラウンドで実行されることを意味
  • -e MONGO_INITDB_ROOT_USERNAME: これはMongoDBの初期化時に使用される環境変数で、MongoDBのルートユーザーのユーザー名を指定する
  • -e MONGO_INITDB_ROOT_PASSWORD: これもMongoDBの初期化時に使用される環境変数で、MongoDBのルートユーザーのパスワードを指定する
  • -p 27017:27017: ホストマシンとコンテナ間でポートのマッピングを行うためのオプションで、ホスト:コンテナの順でポートを指定する(MongoDBのデフォルトポートを指定)
  • --name mongo: コンテナ名
  • mongo: Docker Hubから公式のMongoDBイメージを使用してコンテナを実行するためのイメージ名

コンテナにアクセスしてMongoDBを操作

$ docker exec -it mongo bash
# mongosh -u **** -p pass ****
> show dbs
admin   100.00 KiB
config   12.00 KiB
local    72.00 KiB

ホストからMongoDBを操作するためにクライアントを準備 →下記を参考 www.mongodb.com

接続

$ mongosh mongodb://localhost:27017 -u **** -p ****
> show dbs
admin   100.00 KiB
config   12.00 KiB
local    72.00 KiBhost

これでWSL上にMongoDBのDocker環境が構築された