Ubuntu 换中科大 apt 源、使用阿里源安装 Docker 并配置 Docker 代理

在国内服务器上安装 Docker 时,经常会遇到两个问题:

  1. Ubuntu 默认 apt 源访问慢;
  2. Docker Hub 无法正常拉取镜像。

本文按下面四个步骤完成配置:

  1. 将 Ubuntu apt 源切换为中科大源;
  2. 使用阿里云 Docker CE 源安装 Docker;
  3. 配置 Docker 代理,让 docker pull 走代理;
  4. 使用 hello-world 镜像测试 Docker 是否可用。

本文示例系统为 Ubuntu,命令默认使用 sudo 执行。

一、换中科大 apt 源

中科大 Ubuntu 镜像地址:

https://mirrors.ustc.edu.cn/ubuntu/

先备份当前 apt 源配置:

sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak

查看当前 Ubuntu 版本代号:

lsb_release -cs

假设输出为 jammy,表示 Ubuntu 22.04。将 /etc/apt/sources.list 替换为中科大源:

sudo tee /etc/apt/sources.list > /dev/null <<'EOF'
deb https://mirrors.ustc.edu.cn/ubuntu/ jammy main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ jammy-updates main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ jammy-backports main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ jammy-security main restricted universe multiverse
EOF

如果你的系统不是 Ubuntu 22.04,请把上面的 jammy 替换为你的系统代号:

Ubuntu 20.04: focal
Ubuntu 22.04: jammy
Ubuntu 24.04: noble

更新 apt 索引:

sudo apt update

二、使用阿里源安装 Docker

先安装必要依赖:

sudo apt install -y ca-certificates curl gnupg lsb-release

创建 keyrings 目录:

sudo install -m 0755 -d /etc/apt/keyrings

添加阿里云 Docker CE GPG 公钥:

curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | \
  sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg

设置公钥文件权限:

sudo chmod a+r /etc/apt/keyrings/docker.gpg

添加阿里云 Docker CE 软件源:

echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://mirrors.aliyun.com/docker-ce/linux/ubuntu \
  $(lsb_release -cs) stable" | \
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

更新 apt 索引:

sudo apt update

安装 Docker:

sudo apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

启动 Docker 并设置开机自启:

sudo systemctl enable --now docker

查看 Docker 版本:

docker --version

三、配置 Docker 代理

这里配置的是 Docker daemon 的代理。因为执行 docker pull 时,真正访问 Docker Hub 的是 Docker daemon,而不是当前终端 shell。

假设你的代理地址是:

http://127.0.0.1:7890

如果你的代理不在本机,或者端口不是 7890,请替换成自己的代理地址。

创建 Docker 配置目录:

sudo mkdir -p /etc/docker

编辑 Docker daemon 配置文件:

sudo tee /etc/docker/daemon.json > /dev/null <<'EOF'
{
  "proxies": {
    "http-proxy": "http://127.0.0.1:7890",
    "https-proxy": "http://127.0.0.1:7890",
    "no-proxy": "localhost,127.0.0.1,::1"
  }
}
EOF

检查 JSON 格式:

python3 -m json.tool /etc/docker/daemon.json

重启 Docker:

sudo systemctl restart docker

查看代理是否生效:

sudo docker info | grep -i proxy

如果输出中能看到 HTTP ProxyHTTPS Proxy,说明 Docker 代理已经配置成功。

四、测试 docker pull

使用 Docker 官方测试镜像 hello-world 验证:

sudo docker pull hello-world

运行测试容器:

sudo docker run --rm hello-world

如果看到下面内容,说明 Docker 已经安装成功,并且可以正常拉取 Docker Hub 镜像:

Hello from Docker!
This message shows that your installation appears to be working correctly.

曼波