Skip to main content
05

How do you write a good Dockerfile? (layers, multi-stage, image size)

EasyDockerImagesSecurity

How do you write a good Dockerfile? Cover layer caching, multi-stage builds and image size.

TL;DR

A good Dockerfile produces a small, secure, reproducible image that builds fast. Order instructions from least to most frequently changing, so cached layers are reused: copy the dependency manifest and install dependencies before copying the source. Use a multi-stage build to compile in a full "builder" image and copy only the output into a minimal runtime image. Pin base image versions, run as a non-root user, and keep secrets out of the image.

Key points

  • Each instruction creates a layer; a change invalidates that layer and every layer after it.
  • Use a .dockerignore (node_modules, .git, .env) for smaller build contexts and to avoid leaking secrets.
  • Small bases: -slim, alpine (watch for musl differences), or distroless (no shell or package manager, so less attack surface).
  • Combine apt-get update && apt-get install ... && rm -rf /var/lib/apt/lists/* in one RUN so caches don't stay in a layer.
  • Use the exec form CMD ["node", "server.js"] so the app is PID 1 and receives SIGTERM.
  • Never COPY secrets or pass them as ARG; they stay in the image history. Use BuildKit --mount=type=secret.
  • Pin by tag or digest, and scan images in CI (Trivy, Grype).

Example

dockerfile
# syntax=docker/dockerfile:1
FROM node:22-slim AS build
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN corepack enable && pnpm install --frozen-lockfile
COPY . .
RUN pnpm build && pnpm prune --prod

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

Common follow-ups

  • COPY vs ADD? Prefer COPY. ADD also extracts archives and fetches URLs, which is surprising behavior.
  • CMD vs ENTRYPOINT? ENTRYPOINT is the fixed executable; CMD supplies default arguments that docker run can override.

What interviewers look for

Tip

Cache-friendly ordering, multi-stage builds, non-root, and no secrets in layers, shown in a short Dockerfile.

  • Red flag: COPY . . before installing dependencies, or running as root with latest tags.

Was this helpful?

Related questions