Chapter Five
Building Well
The naive Driftwood image from Chapter 4 is 1.1 GB, runs as root, and bakes its build toolchain and pip cache into the shipped layers. This chapter rebuilds it into a 180 MB slim image with the database password supplied as a build secret — through BuildKit, multi-stage builds, a lean context, cache and secret mounts, deliberate shrinking, and a reproducible, digest-pinned build.
Chapter 4 produced a Dockerfile that works and an image you would never want to ship: 1.1 GB on disk, the full compiler toolchain and pip cache fused into the layers, and a database password sitting readable in docker history. This chapter fixes all of it without changing what Driftwood does — same app, same gunicorn process on :8000, a fraction of the size and none of the leaks.
The spine is the multi-stage build, which alone takes Driftwood from 1.1 GB to roughly 180 MB by leaving the compilers in a discarded builder stage. Around it sit the pieces that make a build fast, small, and trustworthy: BuildKit as the engine that powers the modern --mount instructions, a .dockerignore that keeps the context lean and secrets out of it, cache and secret mounts that fix the worst build-time habits, a deliberate teardown of where the bytes go, and the digest pinning that makes "what shipped in 1.4.0" answerable to the exact byte.
Topics in This Chapter
buildx front door, the DOCKER_BUILDKIT=1 switch, and the # syntax line that unlocks --mount.COPY --from. The single change that drops Driftwood from 1.1 GB to 180 MB..git, virtualenvs, and stray secrets out of the build context — and out of the image when a careless COPY . . would otherwise bake them in. The cheapest fix in the chapter.RUN --mount modes. A cache mount persists pip and apt downloads across builds without becoming a layer; a secret mount hands one step the database password and leaves nothing in history — the real fix for the ARG footgun.RUN, multi-stage to drop the toolchain, and fewer layers. Measured with docker history and dive, not guessed.:latest base that shifted under you.