Opscraft
DevSecOps & secrets management · Lesson 3 of 7 · 3 min read

Container image security

Building secure images

FROM golang:1.23 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/app ./cmd/app

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/app /app
USER 65532:65532
ENTRYPOINT ["/app"]
  • Minimal base images (distroless, Chainguard/Wolfi, Alpine with care, slim variants) — fewer packages = fewer CVEs and no shell for attackers.
  • Multi-stage builds — compilers and build tools stay out of the runtime image.
  • Non-root user, numeric UID (so runAsNonRoot can verify it).
  • No secrets in layers — use BuildKit secret mounts (RUN --mount=type=secret,id=npmrc ...); remember ENV/ARG values and deleted files remain in image history.
  • Pin base images by digest and rebuild regularly to pick up patches (Renovate/Dependabot for base image updates).
  • HEALTHCHECK for non-K8s runtimes; .dockerignore to avoid copying .git, .env, credentials.
  • Lint with hadolint; scan with Trivy in CI and in the registry (ECR enhanced scanning continuously re-scans when new CVEs are published).
Enlarge diagramMinimal basedistroless, Wolfi: fewer CVEs, noshellMulti-stagebuild tools left behindNon-root UIDnumeric, e.g. 10001Pinned by digestbase image never shiftsNo secretsnot in layers or build argsRebuilt oftenpicks up patched bases
Figure 1. A secure image, layer by layer.
Swipe sideways to see all of it, or tap to open it full screen.