配置 Win+WSL 环境下的网络代理

0.背景和需求

  • 背景:win11 安装了 WSL2,并运行了 ubuntu,ubuntu 中安装了 docker。
  • 需求:可以正常运行 docker pull 镜像(不依靠第三方镜像加速站,因为安全性/合规性存疑)。
  • 现状:docker pull 报错超时。
1
2
3
➜  ~ docker pull hello-world
Using default tag: latest
Error response from daemon: Get "https://registry-1.docker.io/v2/": net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)

1.设置 win 系统代理、终端代理

这里不赘述,自行设置,可以走公司合规的网络专线。

验证:win powershell 可以正常 curl https://hub.docker.com/

2.设置 WSL可以使用 win 系统代理

  1. 在文件夹地址栏,输入 %UserProfile%,创建 .wslconfig 文件。
  2. .wslconfig 中写入以下内容。
1
2
3
4
5
6
7
8
[wsl2]
networkingMode=mirrored
dnsTunneling=true
autoProxy=true

[experimental]
# requires dnsTunneling but are also OPTIONAL
bestEffortDnsParsing=true

这段配置主要是 让 WSL2 内的网络和 Windows 镜像,这样 WSL 网络就和 win 完全一致了。

  1. 重启 WSL

验证:WSL2 终端可以正常 curl https://hub.docker.com/

参考:

3.设置 WSL 中 docker 可以使用系统代理

此时虽然 WSL 可以使用系统代理,但是 docker 为守护进程,还需要手动设置代理。

  1. 创建目录。
1
sudo mkdir -p /etc/systemd/system/docker.service.d 
  1. docker.service.d目录下写文件。
1
vim proxy.conf 
  1. 文件中写入以下内容。
1
2
3
4
5
# 这个端口设成你自己的代理端口
[Service]
Environment="HTTP_PROXY=http://127.0.0.1:xxxx"
Environment="HTTPS_PROXY=http://127.0.0.1:xxxx"
Environment="NO_PROXY=localhost,127.0.0.1"

表示docker 使用以上端口进行代理。

  1. 重启docker
1
sudo systemctl restart docker

验证:得到的结果和你配置的端口一样。

1
2
➜  ~ systemctl show --property=Environment docker
Environment=HTTP_PROXY=http://127.0.0.1:7890 HTTPS_PROXY=http://127.0.0.1:7890 NO_PROXY=localhost,127.0.0.1

4.大公告成

docker pull hello-world 正常。

注意,虽然实现了系统代理,但是没法 ping,所以不要用 ping 做测试,ping 走的是 ICMP 协议,系统代理仅代理了 HTTP/HTTPS 应用层协议。


配置 Win+WSL 环境下的网络代理
https://www.aimtao.net/wsl-proxy/
Posted on
2025-08-31
Licensed under