27.1 Image Layers and Layer Caching
Every Dockerfile instruction (FROM, RUN, COPY, ADD) creates a new read-only layer; the union of layers forms the final image filesystem. Docker caches layers by instruction + content hash — reordering instructions so rarely-changing steps come first (dependency installation) and frequently-changing steps come last (application code) maximizes cache reuse and build speed.
# ❌ BAD: cache busts on every code change, re-runs dependency install every time
FROM python:3.11-slim
COPY . .
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
# ✅ GOOD: dependency layer cached separately from code layer
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "app.py"]
27.2 Multi-Stage Builds
Multi-stage builds separate the build toolchain from the runtime image, dramatically shrinking final image size and attack surface.
# Stage 1: Build
FROM node:20 AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Stage 2: Runtime — only ship the compiled output
FROM node:20-slim AS runtime
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]
.NET multi-stage example:
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY *.csproj .
RUN dotnet restore
COPY . .
RUN dotnet publish -c Release -o /app
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS runtime
WORKDIR /app
COPY --from=build /app .
USER app
ENTRYPOINT ["dotnet", "MyService.dll"]
Result: build stage (SDK, compilers, dev dependencies — often 1GB+) never ships; runtime image only contains the compiled artifact plus a minimal base (often <200MB).
27.3 Security Best Practices
| Practice | Why |
|---|---|
Use minimal/distroless base images (-slim, -alpine, gcr.io/distroless/*) |
Fewer packages = smaller attack surface, fewer CVEs to patch |
Run as non-root user (USER appuser) |
Limits blast radius if the container is compromised |
Pin base image versions (not :latest) |
Reproducible builds, avoid silent breaking changes |
| Multi-stage builds | Build tools/secrets never reach the runtime image |
| Scan images in CI (Trivy, Grype, ECR/ACR native scanning, Snyk) | Catch known CVEs before deployment |
| Never bake secrets into image layers | Layers persist in registry history even if a later layer “deletes” the file — use build secrets (--secret mount) or runtime injection instead |
Set read-only root filesystem where possible (readOnlyRootFilesystem: true in K8s) |
Prevents runtime tampering/malware persistence |
Drop unnecessary Linux capabilities (--cap-drop=ALL) |
Least privilege at the kernel-capability level |
| Sign images (Cosign/Notary) and verify signatures at deploy time | Supply-chain integrity — ensures only trusted, unmodified images run |
# Secure Dockerfile pattern
FROM python:3.11-slim AS runtime
RUN groupadd -r appgroup && useradd -r -g appgroup appuser
WORKDIR /app
COPY --chown=appuser:appgroup . .
RUN pip install --no-cache-dir -r requirements.txt
USER appuser
HEALTHCHECK --interval=30s --timeout=3s CMD python healthcheck.py
CMD ["python", "app.py"]
27.4 Interview Q&A
Q1: Walk me through how you’d harden a container image for a production AI service handling sensitive data.
A: Start from a minimal base — distroless or
-slim, never a full OS image — to shrink the CVE surface. Use a multi-stage build so the SDK/compiler/dev dependencies used to build the model-serving code never ship in the runtime image. Run as a non-root user with a read-only root filesystem and dropped Linux capabilities, so a container escape has minimal blast radius. Never bake API keys or model weights with embedded credentials into a layer — inject secrets at runtime via the orchestrator’s secret store (Kubernetes Secrets backed by Key Vault/Secrets Manager, not plain K8s Secrets which are only base64-encoded). Scan the image in CI with Trivy or the registry’s native scanner and fail the build on high/critical CVEs. Sign the image with Cosign and enforce signature verification at admission time in the cluster (via OPA Gatekeeper or Azure Policy) so only images built by the CI pipeline can run.
Q2: Why do multi-stage builds matter beyond just image size?
A: Three reasons beyond size: security (build-time secrets, source maps, and toolchains never reach the runtime image, so there’s nothing to exfiltrate from a running container); attack surface (fewer installed packages means fewer CVEs to track and patch); and build/deploy speed (smaller images pull faster on cold-starting nodes, which matters directly for autoscaling latency in Kubernetes — a 1.2GB image versus a 150MB image can be the difference between a pod being ready in 5 seconds versus 40 seconds during a scale-out event).