WIN10安装Ubuntu子系统,助力Native Docker运行

适用场景

  1. 需要在本地配置认证客户端,与公司认证服务器打通。部分认证服务器对应协议配置对 Linux 兼容性更好,故需要在本地拉起Linux子系统。
  2. 需要在本地拉起 Docker 容器,但不想借助 Docker Desktop 。希望拉起方式更 Native 。

实操流程

开启WSL功能

在搜索框中检索 PowerShell ,右键点击,“以管理员身份运行”

WIN10安装Ubuntu子系统,助力Native Docker运行插图

在 PowerShell 中输入以下命令加载、开启 WSL 功能:

C:\Users\Admin> Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux

下载并安装Ubuntu子系统

Ubuntu18.04 下载地址:https://aka.ms/wsl-ubuntu-1804

您可以在以下地址下载其他 Linux 发行版:旧版 WSL 的手动安装步骤 | Microsoft Docs

【注意】配置 Docker 环境的读者,如果要下载其他版本,请留意所下载的发行版 WSL 内核版本,若版本低于5.8,在后续拉起 dockerd 进程时,会因 nftables 兼容问题导致 iptables 报错,进而导致 dockerd 进程无法启动:
failed to start daemon: Error initializing network controller: error obtaining controller instance: unable to add return rule in DOCKER-ISOLATION-STAGE-1 chain: (iptables failed: iptables –wait -A DOCKER-ISOLATION-STAGE-1 -j RETURN: iptables v1.8.7 (nf_tables): RULE_APPEND failed (No such file or directory): rule in chain DOCKER-ISOLATION-STAGE-1
(exit status 4))

如果您系统中留存着旧版 iptables,您可以尝试将子系统内 iptables 改为旧版本来解决上述问题:

$ sudo update-alternatives –config iptables
There are 2 choices for the alternative iptables (providing /usr/sbin/iptables).

Selection Path Priority Status
————————————————————
* 0 /usr/sbin/iptables-nft 20 auto mode
1 /usr/sbin/iptables-legacy 10 manual mode
2 /usr/sbin/iptables-nft 20 manual mode

Press <enter> to keep the current choice[*], or type selection number: 1
update-alternatives: using /usr/sbin/iptables-legacy to provide /usr/sbin/iptables (iptables) in manual mode

完成下载后,双击安装 Ubuntu 子系统(无需更改任何选选项)。

完成安装后,系统会自动弹出 Ubuntu 终端页面,在其中创建自己的个人用户,并设置密码。

MobaXterm 登录 Ubuntu 子系统

完成上述操作后,MobaXterm 会自动提示 WSL session,双击即可连接到 Ubuntu 终端。

(如果没有安装 MobaXterm,也可以直接使用上述 Ubuntu 安装完成后弹出的终端进行子系统操作。)

WIN10安装Ubuntu子系统,助力Native Docker运行插图1

为了便于使用终端工具(Putty、Secure-CRT 等等)连接,您也可以为子系统配好 ssh 服务,命令如下:

$ apt update
$ apt install openssh-server vim -y
$ service ssh --full-restart

升级 WSL

由于在 WSL 子系统部署 Docker 需要基于虚拟化功能(WSL2 具备虚拟化功能),所以,在部署 Docker 之前,我们要先启动系统的虚拟机功能,并将 WSL 升级到 version 2。继续使用上述 PowerShell 终端,执行命令:

C:\Users\Admin> dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

 命令执行完成后,重启系统。然后检查虚拟化功能是否启动:

WIN10安装Ubuntu子系统,助力Native Docker运行插图2

接着,下载并运行 Linux 内核更新包:

  • x64: https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi
  • arm64: https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_arm64.msi

最后,在 PowerShell 终端,设置 WSL 版本:

wsl --set-version <版本名称> <版本号>

例如:

C:\Users\Admin> wsl --set-version Ubuntu-18.04 2

版本升级会耗费一些时间,如果成功,会出现“转移成功”的回显。

【备注】您可以使用以下命令查看您的版本名称(NAME 对应的字段即是):

C:\Users\Admin> wsl -l -v

安装 Docker

至此,我们完成了子系统的全部配置。

接下来,我们可以使用 MobaXterm 直接在 Ubuntu 子系统中安装、启动 Docker:

$ sudo apt install docker.io -y
$ sudo docker --version
$ sudo dockerd

完成启动后,可以使用 docker run 、docker pull 等命令来做功能验证。关于 docker 的命令部分,这里不再赘述。

参考链接

旧版 WSL 的手动安装步骤 | Microsoft Docs

标签