插件窝 干货文章 Docker中使用apt-get update失败,如何正确配置阿里云镜像源?

Docker中使用apt-get update失败,如何正确配置阿里云镜像源?

Ubuntu multiverse restricted universe 680    来源:    2025-03-14

在Docker容器中使用apt-get update时,如果遇到更新失败的问题,通常是由于默认的软件源服务器在国外,导致访问速度慢或连接不稳定。为了解决这个问题,可以将Docker容器中的软件源配置为阿里云的镜像源,以提高更新速度和稳定性。

以下是配置阿里云镜像源的步骤:

1. 进入Docker容器

首先,进入正在运行的Docker容器:

docker exec -it <container_id> /bin/bash

其中<container_id>是你要进入的容器的ID或名称。

2. 备份原有的源列表文件

在修改之前,建议先备份原有的源列表文件:

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

3. 修改/etc/apt/sources.list文件

使用文本编辑器(如vinano)打开/etc/apt/sources.list文件:

vi /etc/apt/sources.list

将文件内容替换为阿里云的镜像源。以下是Ubuntu系统的阿里云镜像源配置示例:

Ubuntu 20.04 (Focal Fossa)

deb http://mirrors.aliyun.com/ubuntu/ focal main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-proposed main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal-proposed main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal-backports main restricted universe multiverse

Ubuntu 18.04 (Bionic Beaver)

deb http://mirrors.aliyun.com/ubuntu/ bionic main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-proposed main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-proposed main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-backports main restricted universe multiverse

4. 更新软件包列表

保存并退出编辑器后,运行以下命令更新软件包列表:

apt-get update

5. 验证配置

如果apt-get update命令执行成功,说明阿里云镜像源配置正确。

6. (可选)在Dockerfile中配置镜像源

如果你希望在构建Docker镜像时自动使用阿里云镜像源,可以在Dockerfile中添加以下内容:

RUN sed -i 's|http://archive.ubuntu.com/ubuntu/|http://mirrors.aliyun.com/ubuntu/|g' /etc/apt/sources.list && \
    apt-get update

这样,在构建镜像时就会自动使用阿里云的镜像源。

总结

通过以上步骤,你可以将Docker容器中的软件源配置为阿里云的镜像源,从而解决apt-get update失败的问题,并提高软件包更新的速度和稳定性。