Skip to content
masterclass BuddyTech Buzz5 fresh blogs Β· every Monday

The Three Docker Stages That Shrink Every Next.js 16 Image

Build a lean, non-root Next.js 16 Docker image with output file tracing and dodge the 404, EACCES and binding mistakes that break it.

MCB Editorial

Tech Buzz Community Desk Β· 9 min read Β·

New story

Inspired by β€œMy Next.js Docker Image Was 1.97 GB. Standalone Output and Three Stages Took It to 287 MB.” by Waseem Anjum on Medium. Rewritten and expanded by MCB Editorial.

Narrated by Study Buddy Narration
Voiceover Engine β€’ Interactive Audio Sync
0:009:00

Learning Objectives & Key Takeaways

0 / 4 Completed
Architecture Ready
100%
What you will learn
  1. Output file tracing prunes node_modules down to only what each route actually needs.
  2. Standalone output never includes public or .next/static, you must copy both yourself.
  3. A three-stage Dockerfile keeps the full source tree and dependency install out of the final image.
  4. Binding to 0.0.0.0 and chowning files before switching to a non-root user prevent silent failures.
  5. NEXT_PUBLIC_ values are baked in at build time, real secrets belong in runtime environment variables.

The Image That's Bigger Than It Needs To Be

A common first Dockerfile for a Next.js app copies the entire repository, runs npm ci, runs the build, and starts the server with npm start, all in a single stage on top of a full Node image. It works, the app boots, tests pass. But the resulting image carries the whole source checkout, every dev dependency, and often a duplicated node_modules across build layers, which makes every push and pull slower than it needs to be.

Next.js 16 with React 19 doesn't change this problem, and a newer framework version alone won't fix it. The fix is two separate ideas working together: output file tracing, which figures out the minimal set of files a production server actually needs, and a multi-stage Dockerfile, which makes sure only that minimal set crosses into the final image.

In the rest of this story
  1. What Output File Tracing Actually Puts In standalone
  2. Three Stages: deps, builder, runner
  3. The 404 That Standalone Output Is Guaranteed To Give You
  4. Binding and Permissions: 0.0.0.0, the node user, and EACCES
  5. Build-Time Config, Runtime Secrets, and a Cheap Health Check
1 code example Β· 9 min read in full
Member-only story

Checking your membership…

Members read every Tech Buzz story in full, with code examples, audio and the discussion, plus every course, quiz and interview set in the Learning Dashboard.

0

Written by

MCB Editorial

Tech Buzz Community Desk. Contributing deep-dive engineering architectures, cloud paradigms, and system design insights to Master Class Buddy.