93 lines
2.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: docker pull使用代理
createTime: 2026/04/04 14:28:00
tags:
- Docker
- Proxy
---
## 问题现象
当 Docker 所在的环境需要通过代理服务器和互联网连通时,直接拉取镜像会遭遇失败:
```bash
$ 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 配置目录
```bash
sudo mkdir -p /etc/systemd/system/docker.service.d
```
### 2. 创建代理配置文件
新建文件 `/etc/systemd/system/docker.service.d/http-proxy.conf`
```ini
[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` 配置:
```ini
[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
```bash
sudo systemctl daemon-reload
sudo systemctl restart docker
```
### 5. 验证配置
检查环境变量是否正确配置:
```bash
sudo systemctl show --property=Environment docker
```
也可以通过 `docker info` 查看代理配置是否生效。
## 常见误区
Docker 官方有一篇关于[配置代理的文档](https://docs.docker.com/network/proxy/#configure-the-docker-client),但那篇文档讲的是如何给**运行中的容器**配置代理环境变量,而不是给 docker daemon 配置代理来拉取镜像。如果按照那篇文档在 `~/.docker/config.json` 中配置,是无法解决拉取镜像超时的问题的。
## 总结
- 拉取镜像是 docker daemon 的职责
- 需要在 systemd 层面配置 `HTTP_PROXY``HTTPS_PROXY` 环境变量
- 配置路径:`/etc/systemd/system/docker.service.d/http-proxy.conf`
- 配置完成后需要执行 `daemon-reload``restart docker`
## 参考
- [Docker 官方文档 - systemd 代理配置](https://docs.docker.com/config/daemon/systemd/#httphttps-proxy)
- [Stack Overflow - Can't pull docker image behind a proxy](https://stackoverflow.com/questions/69047394/cant-pull-docker-image-behind-a-proxy)