Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 111 Β· Dockerfiles

Dockerfile Best Practices

A practical Dockerfile checklist: small images, cache-friendly ordering, version pinning, non-root users, apt patterns, linting with build checks and hadolint.

Any Dockerfile that builds is a "working" Dockerfile. A good one builds quickly, produces a small image, gives the same result next month as today, runs as an unprivileged user, and is easy for the next person to read. This lesson collects the habits that separate the two, with measurements from real builds so you can see what each habit buys you.

Think of it as a review checklist. You have met every instruction already; here we combine them. If a topic is new, follow the link to its lesson.

The same app, written badly and well

Our app is a tiny Python script and one dependency:

Python
import os, getpass
print("hello from", os.getcwd(), "as", getpass.getuser(), "uid", os.getuid())
TEXT
requests==2.32.3

First, a Dockerfile that works but has several habits you should avoid:

DOCKERFILE
FROM python:3-slim
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
CMD python app.py

Now a reviewed version:

DOCKERFILE
FROM python:3.13-slim

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

RUN useradd --create-home --uid 10001 appuser
WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY --chown=appuser:appuser app.py .

USER appuser
CMD ["python", "app.py"]

Build and run both:

CONSOLE
$ docker build -f bad.Dockerfile -t tcd-app-bad .
$ docker build -f good.Dockerfile -t tcd-app-good .
$ docker image ls
IMAGE             ID             DISK USAGE   CONTENT SIZE   EXTRA
tcd-app-good      ...                181MB
tcd-app-bad       ...                205MB
$ docker run --rm tcd-app-bad
hello from /app as root uid 0
$ docker run --rm tcd-app-good
hello from /app as appuser uid 10001

(The two images use different Python minor versions, so I do not credit the whole 24 MB difference to the Dockerfile style; the pip download cache is part of it.) The most important difference is invisible in the sizes: the first container runs as root, the second as an unprivileged user. Now edit app.py (a one-line change, the most common thing you do) and rebuild each:

CONSOLE
$ docker build --progress=plain -f bad.Dockerfile -t tcd-app-bad .
#5 [1/4] FROM docker.io/library/python:3-slim@sha256:044d5bd7...
#5 CACHED
#6 [2/4] COPY . /app
#7 [3/4] WORKDIR /app
#8 [4/4] RUN pip install -r requirements.txt
$ docker build --progress=plain -f good.Dockerfile -t tcd-app-good .
#6 [2/6] RUN useradd --create-home --uid 10001 appuser
#6 CACHED
#7 [3/6] WORKDIR /app
#7 CACHED
#8 [4/6] COPY requirements.txt .
#8 CACHED
#9 [5/6] RUN pip install --no-cache-dir -r requirements.txt
#9 CACHED
#10 [6/6] COPY --chown=appuser:appuser app.py .

In the bad Dockerfile, the code change invalidated COPY . /app, and every instruction after it re-ran, including the dependency install. In the good one only the final COPY ran. With a real project where pip install or npm ci takes two minutes, this ordering is worth more than any other tip. The rest of the lesson goes through each habit.

1. Order instructions from least to most frequently changing

The build cache (The Build Cache) reuses a layer only if everything before it is unchanged. So write the file like a funnel:

  1. Base image, system packages, users (change rarely).
  2. Dependency manifests (requirements.txt, package*.json, go.mod, pom.xml) and the dependency install.
  3. Your source code (changes constantly).
  4. Metadata and the start command.

Copy the manifest and install before copying the rest of the source. That is the whole trick behind the good Dockerfile above.

2. Start from a small, specific base image

Smaller images pull faster, start faster and contain fewer vulnerabilities. Pick the base carefully (Choosing a Base Image): -slim variants for Debian-based images, alpine when your software is musl-friendly, distroless or scratch for static binaries. And be specific: python:3.13-slim instead of python:latest. The latest tag means "whatever the maintainers pushed most recently", and the default python variants include a full compiler toolchain, so they are several times larger than the 184 MB python:3-slim used here.

3. Pin versions, and know what pinning means

A reproducible build gives the same image from the same Dockerfile. There are three levels of pinning:

  • Floating (python:3): you get new minor versions automatically. Convenient, but a rebuild next week can behave differently.
  • Specific tag (python:3.13-slim): you track patch updates within one minor version. A good default for most teams.
  • Digest (python:3.13-slim@sha256:57b29a7c...): byte-for-byte identical, forever. Find the digest with:
CONSOLE
$ docker buildx imagetools inspect python:3.13-slim --format '{{.Manifest.Digest}}'
sha256:57b29a7c050c4e679e4bea572e14b3965cf4b5839de2da49d55e49ffc4024f39
DOCKERFILE
FROM python:3.13-slim@sha256:57b29a7c050c4e679e4bea572e14b3965cf4b5839de2da49d55e49ffc4024f39
CMD ["python","-c","print(1)"]

I built and ran that file, and it printed 1. A digest pin also means you stop receiving security patches until you update it, so pair it with an automated tool (Dependabot or Renovate) that opens pull requests when a new digest appears. Pin your application dependencies too: requests==2.32.3 in requirements.txt, lock files for npm, go.sum for Go.

Layers are immutable. Deleting a file in a later layer hides it but does not shrink the image. So the download, install and cleanup must be one RUN. Here is the classic Debian package case, built both ways on debian:stable-slim:

DOCKERFILE
FROM debian:stable-slim
RUN apt-get update
RUN apt-get install -y curl ca-certificates
DOCKERFILE
FROM debian:stable-slim
RUN apt-get update \
 && apt-get install -y --no-install-recommends curl ca-certificates \
 && rm -rf /var/lib/apt/lists/*
CONSOLE
$ docker image history tcd-apt-bad --format '{{.Size}}\t{{.CreatedBy}}' | head -2
21.5MB	RUN /bin/sh -c apt-get install -y curl ca-ce…
21.6MB	RUN /bin/sh -c apt-get update # buildkit
$ docker image history tcd-apt-good --format '{{.Size}}\t{{.CreatedBy}}' | head -1
17.8MB	RUN /bin/sh -c apt-get update  && apt-get in…
$ docker image ls
tcd-apt-good   142MB
tcd-apt-bad    184MB

Three problems fixed at once:

  • apt-get update in its own layer stores the package lists forever (21.6 MB) and, worse, gets cached: next month apt-get install may run against a stale list and fail with "404 Not Found". Always update and install in the same RUN.
  • --no-install-recommends skips optional packages that apt would otherwise add.
  • rm -rf /var/lib/apt/lists/* in the same layer removes the lists, so they never get stored.

For other package managers: apk add --no-cache ... (Alpine), pip install --no-cache-dir ..., npm ci followed by npm cache clean --force or a cache mount (BuildKit and buildx). With cache mounts you often no longer need the cleanup tricks, because the cache is not stored in the image at all.

5. Use multi-stage builds for anything that compiles

Compilers, test frameworks and build tools do not belong in the image you ship. Build in one stage, copy the result into a small final stage (Multi-Stage Builds). The final stage for a Go program can be scratch or distroless; for Java a JRE image; for Node a slim image with only production dependencies.

6. Do not run as root

If an attacker finds a flaw in your app, a root process inside the container has far more power than an unprivileged one. Create a user and switch to it, as the good Dockerfile does:

CONSOLE
$ docker image inspect tcd-app-good --format 'user={{.Config.User}} cmd={{json .Config.Cmd}}'
user=appuser cmd=["python","app.py"]

Give the user a fixed numeric UID (10001), because Kubernetes policies and bind-mount permissions work with numbers. Use COPY --chown= so files belong to the app user instead of running a separate chown -R (which would duplicate the files into a new layer). A non-root image also works with the strictest run options; this container started fine with a read-only root filesystem and all Linux capabilities dropped:

CONSOLE
$ docker run --rm --read-only --cap-drop ALL --security-opt no-new-privileges tcd-app-good
hello from /app as appuser uid 10001

Details are in Users and Permissions and Non-Root Users and Capabilities.

7. Use exec form for CMD and ENTRYPOINT

CMD ["python", "app.py"] (exec form) runs Python directly as process 1, so it receives docker stop's SIGTERM. CMD python app.py (shell form) wraps the command in /bin/sh -c, and the shell may swallow the signal. BuildKit's checker flags it:

CONSOLE
$ docker build --check -f bad.Dockerfile .
Check complete, 1 warning has been found!

WARNING: JSONArgsRecommended - https://docs.docker.com/go/dockerfile/rule/json-args-recommended/
...
$ docker build --check -f good.Dockerfile .
Check complete, no warnings found.

See CMD and ENTRYPOINT and Signals, PID 1 and --init.

8. Keep the build context small and secrets out

COPY . . copies everything in the build context. A .dockerignore file keeps .git, node_modules, local .env files, build outputs and your Dockerfiles out of it (Build Context and .dockerignore). Never put real credentials into ENV, ARG or a copied file; use secret mounts (Managing Secrets). Prefer COPY to ADD unless you need its extra features (COPY and ADD).

9. Add metadata and a health check

Labels from the OCI standard (org.opencontainers.image.source, .version, .licenses) make an image traceable, and a HEALTHCHECK lets Docker and Compose know if the app inside is really working (WORKDIR, USER, EXPOSE and LABEL, HEALTHCHECK).

10. One concern per image

A container should do one job: a web server, a worker, a database. Run several containers and connect them with a network or Compose (Introduction to Docker Compose). Avoid process managers and SSH servers inside application images.

Linting your Dockerfile

Use two kinds of automated review.

Built in: docker build --check . (shown above) runs BuildKit's own rules without building. It caught the deprecated MAINTAINER, the legacy ENV key value form, secret-looking variable names and shell-form CMD.

hadolint is a popular third-party linter. It is not installed on the machine used for this course, so the following is a read-only example:

CONSOLE
$ hadolint Dockerfile
Dockerfile:1 DL3007 warning: Using latest is prone to errors if the image will ever update. Pin the version explicitly to a release tag
Dockerfile:4 DL3042 warning: Avoid use of cache directory with pip. Use `pip install --no-cache-dir <package>`

The exact rule numbers and wording depend on the hadolint version; treat the lines above as an illustration of its style. Run it in CI next to your tests.

A review checklist you can copy

Question Good answer
Is the base image specific and small? -slim, alpine, distroless or scratch; not latest
Is the build reproducible? Pinned tags or digests, lock files
Is the cache used well? Manifests and installs before source code
Do install and cleanup share a layer? Yes, or a cache mount is used
Are build tools left out of the final image? Multi-stage build
Does the app run as non-root? USER with a numeric UID
Is CMD/ENTRYPOINT in exec form? Yes
Is .dockerignore present? Yes, with .git, .env, dependencies, outputs
Are secrets absent from layers? Yes; secret mounts or run-time injection
Does docker build --check pass? No warnings (or conscious exceptions)
Is there a health check and OCI labels? Yes for services

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. You edit one source file. Which Dockerfile ordering avoids reinstalling dependencies?

    Cache keys depend on everything before a layer. Copying only the manifest first means the install layer stays cached when only the source changes.
  2. 2. Why is a separate RUN apt-get update line a problem?

    Update and install belong in the same RUN, followed by removing /var/lib/apt/lists in that same layer.
  3. 3. What is the main trade-off of pinning a base image by digest?

    A digest identifies exact bytes. Use Dependabot or Renovate to update it regularly.
  4. 4. Why use COPY --chown=appuser:appuser app.py . instead of COPY app.py . followed by RUN chown -R appuser /app?

    Changing ownership in a later layer rewrites the files into a new layer, increasing size. --chown sets ownership at copy time.
  5. 5. Which command checks a Dockerfile for deprecated or risky patterns without building it?

    BuildKit's --check option runs its built-in rules, such as JSONArgsRecommended and LegacyKeyValueFormat, and reports warnings.

Summary

  • Order instructions from rarely to frequently changing: base, dependencies, source, command. The cache then does most of the work.
  • Choose a small, specific base image; pin tags (and digests when you need exact reproducibility) and use lock files.
  • Keep install, download and cleanup in one RUN (apt-get update with install, --no-install-recommends, remove the lists), or use cache mounts.
  • Use multi-stage builds so compilers and tests never reach the final image.
  • Run as a non-root user with a numeric UID, use COPY --chown, and exec-form CMD/ENTRYPOINT.
  • Maintain a .dockerignore, keep secrets out of layers, add labels and a health check.
  • Lint with docker build --check and (optionally) hadolint, and review with the checklist above.

Next: The Container Lifecycle