Docker

镜像拉取(守护进程)与容器内访问(容器进程)是两件事,分别配置。

1. 让 docker pull 走代理(守护进程)

Docker Desktop(macOS / Windows):设置 → Resources → Proxies,选择 Manual,填写:

  • Web Server (HTTP):http://127.0.0.1:7898
  • Secure Web Server (HTTPS):http://127.0.0.1:7898

部分 Docker Desktop 版本的代理由虚拟机内部发起,127.0.0.1 指向虚拟机本身。如果不生效,请改填 http://host.docker.internal:7898,并在客户端开启共享代理。

Linux 原生 Docker(dockerd 在宿主机上运行):

bash
sudo mkdir -p /etc/systemd/system/docker.service.d
sudo tee /etc/systemd/system/docker.service.d/proxy.conf <<'EOF'
[Service]
Environment="HTTP_PROXY=http://127.0.0.1:7898"
Environment="HTTPS_PROXY=http://127.0.0.1:7898"
Environment="NO_PROXY=localhost,127.0.0.1"
EOF
sudo systemctl daemon-reload && sudo systemctl restart docker

2. 让容器内的程序走代理

容器里的 127.0.0.1 是容器自己,不是宿主机。

  • Docker Desktop:容器可以用 host.docker.internal 访问宿主机:
bash
docker run --rm -e HTTPS_PROXY=http://host.docker.internal:7898 alpine wget -qO- https://github.com
  • Linux 原生 Docker:先在客户端开启共享代理,允许 Docker 网段(例如 172.17.0.0/16),并为容器生成凭据:
bash
cnb share on --cidr 172.17.0.0/16
cnb share credential create docker-dev   # 口令只显示一次
docker run --rm -e HTTPS_PROXY=http://docker-dev:<口令>@172.17.0.1:<端口> alpine wget -qO- https://github.com

共享代理的监听地址与端口以 cnb share status 的输出为准。

3. 构建镜像时

bash
docker build --build-arg HTTPS_PROXY=http://host.docker.internal:7898 .

不要把代理地址和口令写进 Dockerfile 的 ENV,否则会留在镜像层里。