Open this lesson in your favourite AI. It'll walk you through the why, explain the demo, and quiz you on the try-it list.
docker build looks like one command but is really a small DSL with flags that decide cache behavior, build-time variables, multi-stage targets, and target architectures. Misusing --no-cache makes CI 10x slower than it needs to be; not knowing --platform means your ARM laptop builds a broken x86 production image. Each of these flags maps to a real production failure mode that you only learn the expensive way unless you front-load it.
Use a multi-stage Dockerfile to demonstrate --target, --build-arg, --no-cache, and --platform on the same source.
docker build --target deps . and confirm the output stops after the dependency stage — docker history should show no npm run build step.--build-arg NODE_VERSION=18 and then again with --build-arg NODE_VERSION=22 — verify both images exist and run different Node versions via docker run image node --version.--platform, then with --platform=linux/amd64, and compare docker image inspect ... --format '{{.Architecture}}' for each.Use these three in order. Each builds on the one before.
In one paragraph, explain what each of `--no-cache`, `--build-arg`, `--target`, and `--platform` does, like I'm new to Docker builds.
Walk me through how BuildKit decides whether a layer is a cache hit, including the role of instruction text, file checksums, and `--build-arg` values, step by step.
Given a CI build that takes 12 minutes because every PR triggers a full rebuild, explain how you would combine `--target`, layer caching, and a remote cache backend to bring it under 2 minutes.
cat > Dockerfile <<'EOF'
ARG NODE_VERSION=20
FROM node:${NODE_VERSION}-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
FROM node:${NODE_VERSION}-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
FROM gcr.io/distroless/nodejs20-debian12 AS runner
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=deps /app/node_modules ./node_modules
CMD ["dist/server.js"]
EOF
# Build only the deps stage (great for caching dep-installation in CI):
docker build --target deps -t demo:deps .
# Override the Node version at build time:
docker build --build-arg NODE_VERSION=22 -t demo:node22 .
# Force a clean build to debug a flaky cache:
docker build --no-cache -t demo:fresh .
# Cross-compile for ARM64 from an x86 host (and vice versa):
docker buildx build --platform linux/amd64,linux/arm64 -t demo:multi --push .