Multi-Stage Builds for Next.js
Build a minimal production Node/Next.js-style container with a two-stage Dockerfile, non-root user, and .dockerignore.
TL;DR
A multi-stage Dockerfile uses one stage (deps) to install dependencies and a clean final stage (runner) that copies only what is needed to run the app as a non-root user (nextjs, UID 1001).
Why it exists
Shipping compilers, package managers, devDependencies, and build caches inside a production container bloats image size and leaves extra binaries for an attacker to abuse. Multi-stage builds discard everything except the artifacts you explicitly COPY --from=... into the final stage.
Mental model
Think of the deps stage as the workshop and the runner stage as the shipping crate:
deps(node:22-alpine3.21) — installs production dependencies withpackage.jsoncopied first for cache hits.runner(node:22-alpine3.21) — creates groupnodejsand usernextjs(UID 1001), copies runtime files with--chown=nextjs:nodejs, switches toUSER nextjs, and startsnode server.mjs.
labs/docker-multistage-nextComplete minimal HTTP server, multi-stage Dockerfile, .dockerignore, and step-by-step README.
docker build -t mt-multistage-next:lab labs/docker-multistage-nextDo it
Build the image, run it in the background, verify the /healthz endpoint and container UID, then clean up:
# 1. Build the multi-stage image
docker build -t mt-multistage-next:lab labs/docker-multistage-next
# 2. Run the container on port 3000
docker run --rm -d --name mt-next-lab -p 3000:3000 mt-multistage-next:lab
# 3. Verify HTTP response and non-root user
curl -s http://localhost:3000/healthz
# {"status":"ok"}
docker exec mt-next-lab id
# uid=1001(nextjs) gid=1001(nodejs) groups=1001(nodejs)
# 4. Cleanup
docker rm -f mt-next-lab
docker rmi mt-multistage-next:labGotchas
- Forgetting
--chownonCOPY: Files copied from an earlier stage default toroot:root. If the app needs to write to a directory at runtime,USER nextjswill fail withEACCESunless ownership is set. - Using
node:latest: Always pin a specific release/variant tag likenode:22-alpine3.21so CI and local builds use the same runtime. - Running
hadolint:hadolintflags missing version pins,latesttags, and uncleaned caches—keep yourDockerfileclean so CI passes.
Production checklist
- Separate dependency/build stages from the minimal
runnerstage. - Create and switch to a non-root
USERbeforeCMD. - Exclude
.git,node_modules, and docs via.dockerignore. - Pin base image tags (
node:22-alpine3.21) and validate withhadolint.
Check yourself
Check Yourself
1. What does COPY --from=deps --chown=nextjs:nodejs /app/package.json ./ accomplish?
2. Why does the runner stage create a nextjs user (UID 1001) and set USER nextjs?