Skip to Content
Mengty Learns
Containers

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.

tutorialbeginnerTested with docker 29.4.3, node 22.22.3Updated Nov 26, 2026

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:

  1. deps (node:22-alpine3.21) — installs production dependencies with package.json copied first for cache hits.
  2. runner (node:22-alpine3.21) — creates group nodejs and user nextjs (UID 1001), copies runtime files with --chown=nextjs:nodejs, switches to USER nextjs, and starts node server.mjs.
Run it: labs/docker-multistage-next

Complete minimal HTTP server, multi-stage Dockerfile, .dockerignore, and step-by-step README.

docker build -t mt-multistage-next:lab labs/docker-multistage-next

Do 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:lab

Gotchas

  • Forgetting --chown on COPY: Files copied from an earlier stage default to root:root. If the app needs to write to a directory at runtime, USER nextjs will fail with EACCES unless ownership is set.
  • Using node:latest: Always pin a specific release/variant tag like node:22-alpine3.21 so CI and local builds use the same runtime.
  • Running hadolint: hadolint flags missing version pins, latest tags, and uncleaned caches—keep your Dockerfile clean so CI passes.

Production checklist

  • Separate dependency/build stages from the minimal runner stage.
  • Create and switch to a non-root USER before CMD.
  • Exclude .git, node_modules, and docs via .dockerignore.
  • Pin base image tags (node:22-alpine3.21) and validate with hadolint.

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?

Sources