Docker 镜像加速
由于网络原因,国内用户直接从 Docker Hub 拉取镜像速度较慢,配置镜像加速器可以显著提升下载速度。本章将介绍常用的镜像加速方案。
为什么需要镜像加速?
Docker Hub 的服务器位于海外,国内用户拉取镜像时可能遇到:
- 下载速度极慢
- 连接超时
- 拉取失败
镜像加速器通过在国内部署缓存节点,将常用镜像缓存到国内服务器,从而加速下载。
常用镜像加速器
| 加速器 | 地址 | 说明 |
|---|---|---|
| 阿里云 | https://<your-id>.mirror.aliyuncs.com | 需要注册获取专属地址 |
| 腾讯云 | https://mirror.ccs.tencentyun.com | 腾讯云用户推荐 |
| 华为云 | https://mirrors.huaweicloud.com | 华为云用户推荐 |
| 网易 | https://hub-mirror.c.163.com | 公开可用 |
| 中科大 | https://docker.mirrors.ustc.edu.cn | 公开可用 |
| Docker 官方中国镜像 | https://registry.docker-cn.com | 官方提供 |
⚠️ 镜像加速器的可用性可能会变化,建议配置多个加速器作为备选。
Linux 配置方法
编辑 daemon.json
bash
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<EOF
{
"registry-mirrors": [
"https://docker.mirrors.ustc.edu.cn",
"https://hub-mirror.c.163.com",
"https://mirror.ccs.tencentyun.com"
]
}
EOF重启 Docker 服务
bash
sudo systemctl daemon-reload
sudo systemctl restart docker验证配置
bash
# 查看 Docker 信息,确认 Registry Mirrors 已配置
docker info | grep -A 5 "Registry Mirrors"输出示例:
Registry Mirrors:
https://docker.mirrors.ustc.edu.cn/
https://hub-mirror.c.163.com/
https://mirror.ccs.tencentyun.com/Docker Desktop 配置方法
Windows / macOS
- 打开 Docker Desktop
- 点击 Settings(设置)→ Docker Engine
- 在 JSON 配置中添加
registry-mirrors:
json
{
"registry-mirrors": [
"https://docker.mirrors.ustc.edu.cn",
"https://hub-mirror.c.163.com"
]
}- 点击 "Apply & Restart"
阿里云镜像加速器(推荐)
阿里云提供免费的镜像加速服务,速度稳定:
获取加速地址
- 注册/登录 阿里云容器镜像服务
- 进入 "镜像工具" → "镜像加速器"
- 获取你的专属加速地址(格式:
https://<your-id>.mirror.aliyuncs.com)
配置加速器
bash
sudo tee /etc/docker/daemon.json <<EOF
{
"registry-mirrors": ["https://<your-id>.mirror.aliyuncs.com"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker测试加速效果
bash
# 先删除本地镜像(如果存在)
docker rmi nginx:latest
# 拉取镜像并观察速度
time docker pull nginx:latest配置加速器后,拉取速度通常可以从几十 KB/s 提升到几 MB/s 甚至更快。
其他加速方案
使用代理
如果有代理服务器,可以为 Docker 配置代理:
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://proxy.example.com:8080"
Environment="HTTPS_PROXY=http://proxy.example.com:8080"
Environment="NO_PROXY=localhost,127.0.0.1"
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker搭建私有 Registry 镜像
对于企业用户,可以搭建内部的 Registry 镜像缓存:
bash
docker run -d \
--name registry-mirror \
--restart=always \
-p 5000:5000 \
-e REGISTRY_PROXY_REMOTEURL=https://registry-1.docker.io \
registry:2常见问题
加速器不生效
bash
# 确认配置文件格式正确
cat /etc/docker/daemon.json | python3 -m json.tool
# 确认 Docker 已重启
sudo systemctl restart docker
# 查看 Docker 信息
docker info部分镜像无法加速
某些第三方仓库(如 ghcr.io、quay.io)的镜像不经过 Docker Hub,加速器对其无效。可以手动指定镜像源或使用代理。