Sub topic 3
Multi-stage Builds and Docker Layer Storage
Assume you know docker build, docker run, and basic Dockerfile syntax. This chapter focuses on how build artifacts, layers, and caches are stored.
Multi-stage builds: leaving build tools behind
A multi-stage build uses several FROM instructions. Each stage can contain compilers, package managers, and source files. The final stage copies only the files needed at runtime.
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app ./cmd/app
FROM gcr.io/distroless/static-debian12
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]The final image does not include the Go compiler or the source tree. This reduces attack surface and image size.
Inspecting layers
Use history to see commands and their approximate layer sizes:
docker history myapp:devUse image inspect to print the filesystem-layer digests:
docker image inspect --format '{{json .RootFS.Layers}}' myapp:devA large layer often identifies an installation or accidentally copied build artifact.
Digests, copy-on-write, and sharing
Docker stores layers by content-addressed digest. The digest is derived from the layer's contents, so identical layers can be reused rather than stored twice. An image manifest maps a tag to a configuration object and an ordered list of layer digests.
A container starts with those read-only layers. Its writable top layer uses copy-on-write: reading falls through to lower layers, while a changed file is copied into the writable layer before modification.
Registries and local Docker stores share layers by digest. Two images with the same base layer need only one local copy. A pull or push transfers layers that are missing at the destination.
BuildKit caches
A cache mount keeps package-manager downloads outside the image layer:
# syntax=docker/dockerfile:1
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip \
pip install -r requirements.txt
COPY . .The mount speeds later builds, while the downloaded cache is not copied into the final image.
CI runners can share build results through a registry cache:
docker buildx build \
--cache-from type=registry,ref=registry.example.com/app:buildcache \
--cache-to type=registry,ref=registry.example.com/app:buildcache,mode=max \
-t registry.example.com/app:latest --push .Exercise
Why does a multi-stage build usually produce a smaller runtime image?
Show answer
It copies selected runtime artifacts into a new final stage instead of carrying compilers, source files, and build dependencies forward.