ubuntu22.04对Dockerfile调整国内源

选项 A:使用 cat <<EOF 写入

Dockerfile 中,我们需要使用反斜杠 \ 来进行多行折行,并用 && 将命令连接起来,以减少镜像层数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
FROM ubuntu:22.04

# 修改为阿里源并更新系统
RUN tee /etc/apt/sources.list <<EOF
deb https://mirrors.aliyun.com/ubuntu/ jammy main restricted universe multiverse
deb https://mirrors.aliyun.com/ubuntu/ jammy-updates main restricted universe multiverse
deb https://mirrors.aliyun.com/ubuntu/ jammy-backports main restricted universe multiverse
deb https://mirrors.aliyun.com/ubuntu/ jammy-security main restricted universe multiverse
EOF

RUN apt-get update && apt-get install -y \
curl \
git \
&& rm -rf /var/lib/apt/lists/*

选项 B:使用 sed 替换(更优雅、更安全)

如果不想硬编码整段源内容,可以直接使用 sed 命令将官方源的域名 archive.ubuntu.comsecurity.ubuntu.com 替换为阿里的域名。这种方法非常干净,且不容易因为复制粘贴丢掉某一行。

1
2
3
4
5
6
7
8
9
FROM ubuntu:22.04

# 将默认源替换为阿里云源,并更新缓存
RUN sed -i 's/archive.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list && \
sed -i 's/security.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list && \
apt-get update && \
apt-get install -y --no-install-recommends \
curl \
&& rm -rf /var/lib/apt/lists/*

小贴士

  1. 清理缓存:RUN 指令的最后加上 rm -rf /var/lib/apt/lists/*。这可以清理 apt-get update 产生缓存文件,从而大幅度减小 Docker 镜像的体积
  2. 非交互模式: 建议在执行安装时加上 -y--no-install-recommends(不安装非必要的推荐包),确保构建过程不会因为等待用户确认而卡死。