【问题标题】:Dockerfile: How to set apt mirror based on the ubuntu releaseDockerfile:如何根据 ubuntu 版本设置 apt 镜像
【发布时间】:2020-05-27 02:40:37
【问题描述】:

在构建 docker 镜像时,可以通过覆盖 /etc/apt/sources.list 来设置自定义 apt 镜像,例如

FROM ubuntu:focal

RUN echo "deb mirror://mirrors.ubuntu.com/mirrors.txt focal main restricted universe multiverse" > /etc/apt/sources.list && \
    echo "deb mirror://mirrors.ubuntu.com/mirrors.txt focal-updates main restricted universe multiverse" >> /etc/apt/sources.list && \
    echo "deb mirror://mirrors.ubuntu.com/mirrors.txt focal-security main restricted universe multiverse" >> /etc/apt/sources.list
...

如果基础图像是一个变量,例如FROM ${DISTRO},sources.list要根据ubuntu版本调整。

我尝试了$(lsb_release -cs),如下所示:

RUN echo "deb mirror://mirrors.ubuntu.com/mirrors.txt $(lsb_release -cs) main restricted universe multiverse" > /etc/apt/sources.list && \
    echo "deb mirror://mirrors.ubuntu.com/mirrors.txt $(lsb_release -cs)-updates main restricted universe multiverse" >> /etc/apt/sources.list && \
    echo "deb mirror://mirrors.ubuntu.com/mirrors.txt $(lsb_release -cs)-security main restricted universe multiverse" >> /etc/apt/sources.list

但上面写着lsb_release: not found。

解决方法是在运行之前安装包。

RUN apt-get update && apt-get install -y lsb-release

但是,lsb-release 软件包的安装在某些区域可能会非常缓慢。

那么问题来了,有没有合适的方法在使用apt前设置apt源镜像?

【问题讨论】:

    标签: docker ubuntu apt


    【解决方案1】:

    lsb-release 包不包含在最小的 Ubuntu 映像中,但您可以使用/etc/lsb-release 或/etc/os-release 文件代替(第二个常用,参考this answer 进行比较)。

    对于 Dockerfile,只需将 $(lsb_release -cs) 更改为 $(. /etc/os-release && echo $VERSION_CODENAME),您将不会浪费时间更新和安装包。

    【讨论】:

    • 好建议!但是当我在 docker build 中尝试时,结果是source: not found。但它可以通过使用.. /etc/os-release && echo $VERSION_CODENAME 来修复
    • 已更新,Dockerfile RUN 默认使用/bin/sh 而不是/bin/bash,bash 中的source 是an alias 用于.,它在bash 和bourne shell 中都可用。
    【解决方案2】:

    只需使用sed 就地编辑现有的sources.list 文件。以下 sn-p 将就地修改源文件,而不考虑确切的发行版(并且在其他基于 Debian 的发行版上也可以安全运行,但不会修改那里的文件)。

    它将/etc/apt/sources.list中对http://archive.ubuntu.com/ubuntu的所有引用更改为mirror://mirrors.ubuntu.com/mirrors.txt(告诉内置apt客户端从网络获取时自动使用本地镜像)

    sed -i -e 's/http:\/\/archive\.ubuntu\.com\/ubuntu\//mirror:\/\/mirrors\.ubuntu\.com\/mirrors\.txt/' /etc/apt/sources.list
    

    要在Dockerfile 中使用,只需在RUN 这个 - 最好尽可能早在Dockerfile 中使用:

    RUN sed -i -e 's/http:\/\/archive\.ubuntu\.com\/ubuntu\//mirror:\/\/mirrors\.ubuntu\.com\/mirrors\.txt/' /etc/apt/sources.list
    

    【讨论】:

    • 请解释更多。其他想要使用您的解决方案的人有兴趣阅读明确的答案。
    【解决方案3】:

    在 dockerfile 中反映 .. /etc/os-release && echo $VERSION_CODENAME 为 lsb-release

    【讨论】:

      猜你喜欢
      • 2020-06-30
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 2020-02-06
      • 1970-01-01
      • 2023-04-03
      • 2021-04-23
      相关资源
      最近更新 更多