Sub topic 2
Using Docker Build Cache and Image Metadata
Assume you know basic command-line use, docker run, and the difference between an image and a running container.
Using the build cache well
Docker builds an image from instructions. Each instruction can create a layer. Docker reuses a layer when the instruction and its inputs have not changed. This is the build cache.
Copy dependency files before application source. Dependencies change less often, so Docker can reuse their download layer.
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/appIf only application source changes, Docker reuses go mod download. Put frequently changing instructions later. Keep unrelated files out of the build context with .dockerignore.
Choosing a base image
A base image supplies the operating-system files and tools available in the image. Smaller images usually download faster and contain fewer packages to patch. However, minimal images can make debugging and native-library compatibility harder.
Choose a maintained image with a suitable runtime, architecture, and support policy. Pinning a version is more repeatable than using latest.
Multi-stage builds for smaller images
A multi-stage build uses separate build and runtime stages. The runtime stage copies only the files needed to run the application.
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 compiler and source code remain in the build stage. They are not shipped in the final image.
Digests and content addressing
A digest is a cryptographic identifier for exact image content. A tag such as app:1.0 can be moved to different content. A digest reference cannot change without changing its value:
alpine@sha256:<digest>Use digests when repeatability and supply-chain review matter.
Manifests, configs, and the OCI format
An image manifest describes an image. It points to the configuration object and layer blobs by digest. The configuration records metadata such as the command, environment, and root filesystem layer list. OCI, the Open Container Initiative, defines portable formats for these objects.
What a registry does
A registry stores and serves image blobs, manifests, and tags. Docker pushes missing blobs and a manifest. Docker pulls the manifest, then downloads the required layers. Registries may also store an image index that points to platform-specific manifests.
Exercise
Why should dependency files be copied before application source in a Dockerfile?
Show answer
Dependency files change less often, so Docker can reuse the dependency-download layer when only source code changes.