Wednesday, April 6, 2022

[SOLVED] Dockerfile: How to set apt mirror based on the ubuntu release

Issue

While building a docker image, it's possible to set the custom apt mirror by overwriting the /etc/apt/sources.list, e.g.

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
...

If the base image is a variable, e.g. FROM ${DISTRO}, the sources.list should be adjusted based on the ubuntu release.

I tried $(lsb_release -cs) like below:

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

But it says lsb_release: not found.

The workaround is to install the package before running it.

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

However, the install of lsb-release package could be very slow in some areas.

So the question is, is there a proper way to set the apt source mirror before using apt?


Solution

The lsb-release package is not included in the minimal Ubuntu image, but you could make use of /etc/lsb-release or /etc/os-release file instead (the second one is in common use, refer to this answer for comparison).

For Dockerfile, just change $(lsb_release -cs) to $(. /etc/os-release && echo $VERSION_CODENAME), you won't waste time in updating and installing packages.



Answered By - abuccts
Answer Checked By - David Goodson (WPSolving Volunteer)