'Install build-essential in Docker image without having to do `apt-get update`?

I have a Dockerfile which starts with the following:

FROM python:3.7-slim

RUN apt-get update && apt-get install build-essential -y

Problem is, this layer is always changing, so when I run docker build -t <mytag> ., this layer (and subsequent ones) run again, which takes up significant time.

Is there a way to install build-essential in my Dockerfile in a layer which doesn't constantly change?


EDIT: I had a COPY line before RUN, which I removed from the question as I didn't want to include the names of private files, but it didn't occur to me that that was what was making the build re-run from this step.



Solution 1:[1]

"Is there a way to install build-essential in my Dockerfile in a layer which doesn't constantly change?"

Even the question "having some age", is a case in which the construction of the image can be used in multiple stages. The code below uses an example with a Python App.

# first stage
FROM python:3.8 AS builder
COPY requirements.txt .

# install dependencies to the local user directory (eg. /root/.local)
RUN pip install --user -r requirements.txt

# second unnamed stage
FROM python:3.8-slim
WORKDIR /code

# copy only the dependencies installation from the 1st stage image
COPY --from=builder /root/.local /root/.local
COPY ./src .

# update PATH environment variable
ENV PATH=/root/.local:$PATH

CMD [ "python", "./server.py" ]

I hope it will be useful.

src: Containerized Python Development – Part 1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dawid Laszuk