Lesson content
Read, practise, then check your understanding
Best Practices: Image Optimization and Security
Image quality affects download time, cold start, patch effort, and security exposure. A good image contains the application runtime and only what it needs, has traceable inputs, runs with restricted privilege, and is continuously rebuilt as dependencies receive fixes.
Core ideas
- Multi-stage builds leave compilers and source in a build stage while copying only runtime artifacts forward.
- A non-root
USER, read-only filesystem, dropped capabilities, and restricted mounts reduce runtime power. - Small trusted base images reduce packages, but operational tools may need an external debug workflow.
.dockerignore, secret mounts, and disciplined build arguments prevent unwanted material from entering layers.
How it works
Pin inputs, install dependencies reproducibly, combine cache-friendly steps, and use BuildKit cache or secret mounts where appropriate. Scan operating-system and language packages, produce provenance and an SBOM, sign release artifacts if policy requires it, and rebuild rather than patch running containers.
Command or configuration example
FROM golang:1.24-alpine AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -o /out/api ./cmd/api
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/api /api
USER nonroot:nonroot
ENTRYPOINT ["/api"]
Run examples first in a disposable environment. Replace image names, versions, credentials, ports, paths, and resource values with reviewed settings appropriate to your system.
Production guidance
- Never place secrets in
ARG,ENV, copied files, or earlier layers. - Set CPU, memory, process, and filesystem restrictions at runtime; image settings alone are insufficient.
- Patch by rebuilding from updated trusted inputs, then redeploy the immutable image.
The chapter quiz follows this lesson and checks the concepts as well as the operational tradeoffs.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.