在 Windows 的環境,要使用 Docker 除了 Docker Desktop 之外,也可以使用 WSL + Docker 來完成環境的搭建

通過 Windows Terminal 執行命令
https://apps.microsoft.com/detail/9n0dx20hk701?hl=zh-TW&gl=TW
開發環境
- Windows 11 Home
- PowerShell 7.4.6
- WLS2
安裝 Windows Subsystem for Linux (WSL)
- 以 Administrator 執行 Windows Terminal 。
- 使用以下命令安裝 WSL和啟用虛擬化功能:
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
- 完成後,重新啟動電腦。
- 重啟後,執行以下命令 WSL 設定為版本 2
wsl --set-default-version 2
安裝 Ubuntu 24.04.1 LTS
方法一:Microsoft Store
https://apps.microsoft.com/detail/9nz3klhxdjp5?hl=zh-tw&gl=TW
方法二: WSL 命令行安装
列出可用的版本
wsl -l -o
╰─ wsl -l -o
以下是可安裝的有效發佈的清單。
使用 'wsl.exe --install <Distro>' 安裝。
NAME FRIENDLY NAME
Debian Debian GNU/Linux
SUSE-Linux-Enterprise-15-SP5 SUSE Linux Enterprise 15 SP5
SUSE-Linux-Enterprise-15-SP6 SUSE Linux Enterprise 15 SP6
Ubuntu Ubuntu
Ubuntu-24.04 Ubuntu 24.04 LTS
kali-linux Kali Linux Rolling
openSUSE-Tumbleweed openSUSE Tumbleweed
openSUSE-Leap-15.6 openSUSE Leap 15.6
Ubuntu-18.04 Ubuntu 18.04 LTS
Ubuntu-20.04 Ubuntu 20.04 LTS
Ubuntu-22.04 Ubuntu 22.04 LTS
OracleLinux_7_9 Oracle Linux 7.9
OracleLinux_8_7 Oracle Linux 8.7
OracleLinux_9_1 Oracle Linux 9.1
安裝 Ubuntu 24.04.1 LTS
wsl --install -d Ubuntu-24.04
配置 Ubuntu


安裝 Docker
升級套件
- 開啟 Windows Terminal
- 選擇 Ubuntu 24.04.1 LTS
- 執行以下命令
sudo apt update && sudo apt upgrade -y
sudo apt install -y --no-install-recommends apt-transport-https ca-certificates curl gnupg
安裝中,如下圖:

安裝 Docker
. /etc/os-release
curl -fsSL https://download.docker.com/linux/${ID}/gpg | sudo tee /etc/apt/trusted.gpg.d/docker.asc
echo "deb [arch=amd64] https://download.docker.com/linux/${ID} ${VERSION_CODENAME} stable" | sudo tee /etc/apt/sources.list.d/docker.list
sudo apt update && sudo apt install -y docker-ce docker-ce-cli containerd.io
安裝過程如下圖:

安裝完之後就可以使用 docker versio,查看目前 docker 的版本,但是出現授權的問題,如下圖:

配置 Docker 授權
將當前使用者加入 Docker 群組
sudo usermod -aG docker $USER
更新 Docker 群組設定
sudo sed -i -e 's/^\(docker:x\):[^:]\+/\1:36257/' /etc/group
重新初始化 WSL,離開當前頁簽,Ctrl+D,在 Powershell 輸入
wsl --shutdown
Note:WSL 沒有重啟的命令,只要 shutdown 之後,再進入 wsl 就會啟動了

檢測 Docker
這次再查看 docker version 時,就沒有出現問題了,如下圖:

用 docker 運行 ubuntu 試試看
docker run -it ubuntu bash
如下圖:

心得
這個方法就可以不需要在 Windows 上安裝 Docker Desktop,感覺更輕量些了,吧?
實作的過程如果要重來一遍,先取消註冊
wsl --unregister Ubuntu-24.04
安裝
wsl --install -d Ubuntu-24.04
在 Windows Terminal 再進入 Ubuntu-24.04,就可以拿到一個新的環境。

若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET