Building Good Images

Write Dockerfiles that produce small, fast-building, reproducible and secure images using layers, caching and multi-stage builds.

Intermediate · about 8 hours · difficulty 3/5

Learn first: Containers and Docker Basics

Image quality directly affects build speed, deploy speed, cost and security. A 1.5 GB image full of compilers is slower to pull and has a larger attack surface than a 60 MB one.

Dockerfile essentials

  • FROM, WORKDIR, COPY, RUN, ENV, ARG, EXPOSE, USER, ENTRYPOINT vs CMD.
  • Each instruction creates a layer; order them from least to most frequently changing so the build cache works. Copy the dependency manifest and install dependencies before copying source.
  • Use a .dockerignore to keep node_modules, .git and secrets out of the build context.

Multi-stage builds

Build in a full SDK image, then copy only the output into a slim runtime image (-slim, Alpine, distroless or scratch for static Go binaries).

Reproducibility and tagging

Pin base images by version (or digest), tag your images with the git SHA plus semantic versions, and avoid relying on latest in deployments. BuildKit features such as cache mounts and docker buildx for multi-architecture (amd64/arm64) images are worth learning.

Runtime correctness

Use exec-form ENTRYPOINT ["app"] so signals reach your process, add a HEALTHCHECK where useful, run as a non-root USER, and log to stdout/stderr.

Good enough to move on: you can take a naive Dockerfile and cut its size and rebuild time dramatically, and explain every line.

Key concepts

  • Dockerfile instructions
  • Layer caching order
  • .dockerignore
  • Multi-stage builds
  • Slim, distroless and scratch bases
  • ENTRYPOINT vs CMD and signals
  • Tagging with git SHA
  • buildx and multi-arch images

Mini project

Containerise an app you wrote with a multi-stage Dockerfile, non-root user and .dockerignore, and record image size and cached rebuild time before and after each optimisation.

Check yourself

Why does copying the whole source tree before installing dependencies make every rebuild slow?

Free resources