2.9 KiB
Raw Blame History

title, createTime, tags
title createTime tags
docker pull使用代理 2026/04/04 14:28:00
Docker
Proxy

问题现象

当 Docker 所在的环境需要通过代理服务器和互联网连通时,直接拉取镜像会遭遇失败:

$ docker pull busybox
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)

原因分析

拉取镜像是 docker daemon 的职责,而不是 docker 客户端。因此,仅仅在 shell 中设置 HTTP_PROXY 环境变量是不够的,我们需要让 docker daemon 知道代理服务器的存在。

由于 docker daemon 由 systemd 管理,所以需要在 systemd 配置中设置代理环境变量。

解决方案

1. 创建 systemd 配置目录

sudo mkdir -p /etc/systemd/system/docker.service.d

2. 创建代理配置文件

新建文件 /etc/systemd/system/docker.service.d/http-proxy.conf

[Service]
Environment="HTTP_PROXY=http://proxy.example.com:port"
Environment="HTTPS_PROXY=http://proxy.example.com:port"

:::tip 如果代理服务器需要认证,格式为:http://username:password@proxy.example.com:port :::

3. 配置私有仓库绕过代理(可选)

如果有私有镜像仓库需要直连,添加 NO_PROXY 配置:

[Service]
Environment="HTTP_PROXY=http://proxy.example.com:port"
Environment="HTTPS_PROXY=http://proxy.example.com:port"
Environment="NO_PROXY=your-registry.com,10.10.10.10,*.example.com"

多个地址用逗号分隔,支持通配符 *。如果设置 NO_PROXY=*,则所有请求都不通过代理。

4. 重载配置并重启 Docker

sudo systemctl daemon-reload
sudo systemctl restart docker

5. 验证配置

检查环境变量是否正确配置:

sudo systemctl show --property=Environment docker

也可以通过 docker info 查看代理配置是否生效。

常见误区

Docker 官方有一篇关于配置代理的文档,但那篇文档讲的是如何给运行中的容器配置代理环境变量,而不是给 docker daemon 配置代理来拉取镜像。如果按照那篇文档在 ~/.docker/config.json 中配置,是无法解决拉取镜像超时的问题的。

总结

  • 拉取镜像是 docker daemon 的职责
  • 需要在 systemd 层面配置 HTTP_PROXYHTTPS_PROXY 环境变量
  • 配置路径:/etc/systemd/system/docker.service.d/http-proxy.conf
  • 配置完成后需要执行 daemon-reloadrestart docker

参考