Why and how do you use multi-stage builds from a security point of view?
IntermediateScenarioContainer and IaC Security
Answer
Situation read → Build tools, source code and caches in the final image add CVEs and help an attacker.
What I'd do →
- Build in one stage, copy only the artifact to a minimal final stage:
FROM golang:1.23 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app ./cmd/app
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]
- Pin base images by digest.
- Keep
.dockerignorestrict (.git,.env,*.pem).
Why → The final image contains only what runs.
Interview tip → Mention .dockerignore as a common source of leaked files.
More on Container and IaC Security
A team asks whether to use `ubuntu`, `alpine` or a distroless base image. How do you advise?Beginner`trivy image` shows 300 vulnerabilities in your app image. How do you bring this down?BeginnerA Dockerfile runs the app as root. How do you fix it and prove the fix?IntermediateCheckov fails a Terraform PR because an S3 bucket allows public access. What do you change?BeginnerHow do you set up image scanning so nothing vulnerable reaches production?IntermediateAn image passed scanning three weeks ago and runs in production. A new critical CVE is published today. What happens next?Intermediate