Docker 代理配置机制与作用域
Docker 中的代理配置存在多个作用层级, 不同配置方式影响的范围完全不同。本文基于官方文档,对各层代理机制梳理说明, 以便区分。
Docker CLI 代理配置
配置文件: ~/.docker/config.json, 这个配置主要是针对 docker CLI 以及 docker compose 生效,配置示例如下:1
2
3
4
5
6
7
8
9{
"proxies": {
"default": {
"httpProxy": "http://127.0.0.1:1234",
"httpsProxy": "http://127.0.0.1:1234",
"noProxy": "localhost,127.0.0.1"
}
}
}
官方文档: https://docs.docker.com/engine/cli/proxy/
作用范围
对 build 的影响
在执行:1
2docker build
docker compose build
时,CLI 会将 proxy 自动转换为 build-args:
- HTTP_PROXY
- HTTPS_PROXY
- NO_PROXY
官方说明:
Proxy settings are automatically passed as build arguments.
对应文档: https://docs.docker.com/engine/cli/proxy/#configure-the-docker-client
对容器运行的影响
当执行:1
2docker run
docker compose up
CLI 会自动将 proxy 注入为容器环境变量。
官方文档原文:
When you start a container, proxy environment variables are automatically set.
注意:该行为仅发生在使用当前 SHELL 用户执行 Docker CLI 创建容器时。
Dockerfile 中 ARG 与 ENV 的语义边界
官方文档:
- ARG: https://docs.docker.com/engine/reference/builder/#arg
- ENV: https://docs.docker.com/engine/reference/builder/#env
ARG
1 | ARG HTTP_PROXY |
- 仅在构建阶段可用
- 不会自动出现在最终镜像的环境变量中
- 必须通过
--build-arg显式传入
官方说明:
ARG is not persisted in the final image.
ENV
1 | ARG HTTP_PROXY |
- 会写入镜像元数据
- 运行容器时自动存在
- 可被
docker run -e覆盖
官方说明:
The ENV instruction sets environment variables in the image.
Docker Daemon(dockerd)代理
systemd 配置方式, 创建如下文件1
/etc/systemd/system/docker.service.d/http-proxy.conf
内容如下:1
2
3
4[Service]
Environment="HTTP_PROXY=http://127.0.0.1:1234"
Environment="HTTPS_PROXY=http://127.0.0.1:1234"
Environment="NO_PROXY=localhost,127.0.0.1"
更新文件后, 使用 systemctl daemon-reload 重新加载, 并使用 systemctl restart docker 重启生效。
官方文档:https://docs.docker.com/config/daemon/systemd/#httphttps-proxy
作用范围
文档明确指出:
These environment variables configure the Docker daemon.
即:
仅影响 dockerd 自身网络行为,包括:
- docker pull
- docker login
- registry 通信
不会影响:
- Dockerfile 构建阶段
- 容器运行阶段环境变量
作用域对比
| 配置方式 | 影响拉取镜像 | 影响 build | 影响容器环境 |
|---|---|---|---|
| ~/.docker/config.json | ❌ | ✅ | ✅ |
| Dockerfile ARG | ❌ | ✅ | ❌ |
| Dockerfile ENV | ❌ | ✅ | ✅ |
| dockerd systemd proxy | ✅ | ❌ | ❌ |
常见误区
误区 1:ARG 会自动进入运行时容器
错误。
ARG 仅存在于构建阶段, 除非显式转换为 ENV。
误区 2:config.json 仅影响 build
错误。
官方文档说明:
Proxy settings are used when starting containers.
因此同时影响 docker build 和 docker run命令。
推荐实践
构建阶段
显式传参:1
2
3docker build \
--build-arg HTTP_PROXY=... \
--build-arg HTTPS_PROXY=...
避免将代理写死在镜像中。
运行阶段
在 compose 文件中显式声明:1
2environment:
HTTP_PROXY: http://proxy:1234
不要依赖 CLI 自动注入。
Daemon 代理(最常用)
仅在宿主机需要代理访问 registry 时启用,比如在你拉镜像遇到网络问题的时候, 除了找镜像源, 你还可以走代理直接下载官方的 registry。