Friends don't let friends apt-update in Dockerfiles
One common anti-pattern that keeps popping up is the use of package updates in Dockerfiles. A simple search on github.com reveals 1M+ results! Can we do better?
The issue when
you include apt-get update in your Dockerfile or Containerfile, you’re essentially telling Docker to fetch the latest package information every time you build your image, what this means in practice:
- You’re image is likely ending up with different package versions each time you build it, this can lead to potential compatibility issues and makes your builds non-deterministic.
- You’re increasing the build time unnecessarily.
- You’re adding another dependency on a network resource - your build could fail if the package repository is unavailable, even if no updates were pending.
- You work against Docker’s layer caching as the update layer will frequently change, causing all subsequent layers to be rebuilt.
You perhaps should
build a new source image instead and keep using that. When you need a new set of packages, you rebuild the base image.
Create a base image
FROM ubuntu:20.04
RUN apt-get update && apt-get install -y \
package1 \
package2 \
package3 \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
push it to your registry
docker build -t org/base:v1 .
docker push org/base:v1
and depend on that…
FROM myorg/mybase:v1
...
COPY . /app
RUN ...