Multi-stage Dockerfile for Next.js

devops
Docker
scaffolding
zen
Remix

Optimized production Dockerfile with minimal image size and security best practices.

12/8/2025

Prompt

Multi-stage Dockerfile for Next.js

Create an optimized production Dockerfile for a Next.js application.

Stages

1. Base Stage

  • Use Node.js Alpine image (minimal size)
  • Set working directory

2. Dependencies Stage

  • Install all dependencies (dev + prod)
  • Leverage layer caching

3. Builder Stage

  • Copy source code
  • Build Next.js application
  • Generate optimized production build

4. Runner Stage (Final)

  • Production-only dependencies
  • Copy built files from builder
  • Minimal runtime environment

Security Best Practices

Run as Non-Root User

  • Create and use non-privileged user
  • Minimize attack surface

Minimal Image

  • Alpine Linux base
  • Only production dependencies
  • Remove unnecessary files

Optimizations

Layer Caching

  • Optimal instruction ordering
  • Cache dependencies separately from source

.dockerignore File

  • Exclude node_modules, .git, etc.
  • Reduce build context size

Health Check

  • Add HEALTHCHECK instruction
  • Monitor container health

Environment Variables

  • Support runtime configuration
  • Use ENV and ARG appropriately

Local Development

docker-compose.yml

  • Include Next.js service
  • Database service (PostgreSQL/MySQL)
  • Volume mounts for hot reload
  • Environment configuration

Target

  • Final image size: Under 150MB
  • Include comments explaining each optimization
  • Production-ready and secure

Tags

docker
nextjs
optimization
security

Tested Models

gpt-4
claude-3-5-sonnet

Comments (0)

Sign in to leave a comment

Sign In