Containerizing Next.js Apps with Docker
Containerizing a Next.js application seems straightforward until you try to optimize image size, build time, and runtime performance. Here is the Docker setup we use in production, refined over two years of deploying Next.js apps.
Multi-Stage Build
Use a three-stage Dockerfile: dependencies, builder, and runner. The dependencies stage installs node_modules. The builder stage copies source code and runs next build with output standalone. The runner stage copies only the standalone output, public folder, and static files. This produces an image under 200MB instead of the 1.5GB you get from a naive single-stage build.
Standalone Output Mode
Next.js standalone output mode (output: standalone in next.config.js) traces your application imports and produces a minimal Node.js server with only the dependencies your app actually uses. The output includes a server.js entrypoint that you run directly — no need for next start or the full Next.js CLI in your production image.
Layer Caching Strategy
Copy package.json and lockfile before source code so Docker caches the npm install layer. Only source code changes trigger a rebuild, not dependency installation. For monorepos using turborepo, use turbo prune to extract only the packages needed for the target app before building the Docker image.
Runtime Configuration
Set HOSTNAME to 0.0.0.0 so the server listens on all interfaces inside the container. Pass environment variables at runtime, not build time, for secrets and configuration that changes per environment. Use a non-root user in the runner stage for security. Set NODE_ENV to production and configure memory limits with the --max-old-space-size Node.js flag.
Health Checks and Graceful Shutdown
Add a Docker HEALTHCHECK that calls your health endpoint. Handle SIGTERM in your application to gracefully close database connections and finish in-flight requests before the container stops. The default Docker stop timeout is 10 seconds — make sure your graceful shutdown completes within that window or configure a longer timeout.
Written by AIDToolStack Editorial
The AIDToolStack editorial team reviews developer tools, AI products, and MCP servers with hands-on testing and honest assessments. We use the tools we review every day in production.
References & Further Reading
Related Posts
Sponsor Our Newsletter
Reach thousands of developers who are actively evaluating AI tools, MCP servers, and dev infrastructure. Our weekly newsletter goes to engaged technical decision-makers.
All sponsored content is clearly labeled per our editorial policy.