Nextjs Multi-Stage Docker

Nextjs Docker Optimization: Single vs. Multi-Stage Builds

Side-by-side Next.js Dockerfiles: one-stage vs multi-stage, with a documented size tradeoff

This repository ships two build paths for the same style of Next.js app: a single-stage Dockerfile that keeps build tooling in the final image, and a multi-stage Dockerfile that ends on a slimmer runtime image with practices like a non-root user. The README walks through build stages, a compose command to build both, and a table comparing size, build time, complexity, and security posture.

When it is useful

You are deciding how to containerize a Next app, you need concrete examples for a talk or internal standard, or you want numbers you can reproduce with docker images after following the project. It is a comparison demo, not a managed hosting product.

What you can do

  • Build and run both variants with the Docker Compose flow in the repository (ports for each variant are documented there for local comparison only).
  • Read the documented image-size snapshot and methodology. Figures in the README are project-specific; your app may differ.
  • Reuse the patterns (dependency stage, builder, minimal runner) when authoring your own production Dockerfile.

Limits

  • Reported sizes and percentages are from the bundled sample at the time documented in the repo; re-measure after dependency or framework upgrades.
  • Security and compliance still depend on your base images, patching, secrets, and runtime config.
  • The sample does not replace CI scanning, supply-chain review, or orchestration choices.

Frequently asked questions

What does this repo compare?

Two Docker build paths for the same style of Next.js app: a single-stage Dockerfile that keeps build tooling in the final image, and a multi-stage Dockerfile with dependency, builder, and runner stages ending on a slimmer runtime image.

How do I compare them locally?

Copy .env.sample to .env, then docker-compose up --build. Single-stage runs at localhost:3000 and multi-stage at localhost:3001. Use docker images | grep frontend to compare sizes.

What size difference does the README document?

For the bundled sample at the time documented, single-stage was about 1.22GB and multi-stage about 192MB (roughly 84% smaller). Re-measure after dependency or framework upgrades; your app may differ.

What security practice does multi-stage show?

The multi-stage runner uses a non-root user and excludes build tools and development dependencies from the final image. Broader security and compliance still depend on your base images, patching, and secrets.

Continue exploring