Docker & Containers (50 Qs)•Part 3: Advanced Internals, Scale & Production Security (Senior / Lead)
Multi-Stage Builds & Distroless Images: Shrinking Images by 95%.
senior LevelCode ExampleSecurity & AuthDocker & Containers
In Simple Words: Shipping build tools (compilers, npm, Maven, SDKs, bash) into production container images creates massive 1GB+ bloated images riddled with CVE security vulnerabilities:
- Multi-Stage Build: Compile code in a fat build stage, then copy only the final compiled artifact into a minimal runtime base image.
- Google Distroless Images: Contains only your application binary and minimal runtime dependencies (glibc/openssl). Contains zero package managers and zero shell binaries (
/bin/sh), completely neutralizing reverse-shell exploits!
dockerfile
# Stage 1: Build environment
FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o server .
# Stage 2: Distroless production container (Only 15MB total size!)
FROM gcr.io/distroless/static-debian12
COPY --from=builder /app/server /server
USER nonroot:nonroot
ENTRYPOINT ["/server"]