Yashotantra Academy logo

1 · Container Optimization

1. Hardening Docker Images & Multi-Stage Builds

Optimizing layer caching, compiling minimal distroless runtimes, and non-root execution.

9 min read · 2 MCQs

Layer Caching & Order of Execution

Docker builds images as read-only layers. Order instructions from least frequently changed (OS dependencies, package manifests) to most frequently changed (source code) to maximize layer cache hits in CI runners.

FROM node:22-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM gcr.io/distroless/nodejs22-debian12
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
USER nonroot:nonroot
CMD ["dist/server.js"]

Distroless & Non-Root Containers

Standard OS base images bundle package managers, shells, and binaries (curl, bash) that expand the CVE attack surface. Distroless images contain strictly your application and runtime dependencies, eliminating shell-spawn exploits.

Chapter quiz

2 questions · pass mark 75%
  1. 1. Why are build dependencies placed in an earlier multi-stage phase?

  2. 2. What security risk does running as nonroot mitigate?