Docker for Node and Next.js apps · mid
Multi-stage builds for Node and Next.js
A multi-stage Dockerfile builds the app in one stage with all dev dependencies and tools, then copies only the built output and production dependencies into a small final stage that runs as a non-root user.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Each FROM starts a stage; name them (FROM node:24-slim AS build) and copy between them with COPY --from=build. Stages can build in parallel; docker build --target test builds just one.
- Typical Node API: stage 'deps' (npm ci), stage 'build' (tsc or bundler), stage 'runtime' (npm ci --omit=dev or copy pruned node_modules, copy dist/, USER node, CMD ["node", "dist/server.js"]).
- Next.js: set output: 'standalone' in next.config; the runtime stage copies .next/standalone, .next/static and public, then runs node server.js. Docker's own Next.js guide follows this pattern with a node:24 slim base, USER node and an npm cache mount.
- The final image has no compilers, no dev dependencies and no source maps you did not intend to ship: smaller, faster to pull, fewer CVEs.
- Native modules (sharp, bcrypt) must be built for the runtime's OS and libc: alpine uses musl, slim uses glibc; build and run on the same base family.
- NEXT_PUBLIC_ variables are inlined at build time, so they must be set during docker build (or the image is environment-specific).
The red pen
Common traps: mistake → fix
Mistake: Copy the whole build stage into the runtime
Fix: you ship dev dependencies, source and tools again.
Mistake: Build on alpine, run on slim (or the reverse)
Fix: native modules compiled for one libc can fail on the other.
Mistake: Set NEXT_PUBLIC_API_URL at docker run time
Fix: it was already baked into the client bundle at build time.
Easy to hard
Questions interviewers ask, easy to hard
- What is a multi-stage build and why use it?
- Write the stages for a TypeScript Express API.
- How do you containerise a Next.js app? What does output: 'standalone' do?
- Why does the same image need rebuilding for staging and production in some Next.js apps?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.