The Twelve-Factor App model has been the standard way to ship cloud services for years: build one immutable Docker image, then configure staging or production at runtime with environment variables.
The catch is that this disables some of Next.js's best features. NEXT_PUBLIC_* client values, asset prefixes, static pages, and bundle optimizations are baked in during next build. Trying to force everything to runtime either blocks static optimization or forces ugly placeholder-swap hacks at container startup.
Instead of fighting the framework, split the single Dockerfile into three separate images:
- Base image: OS, Node runtime, and global tools (shared across every environment).
- Dependency builder image:
package.jsonand lockfile installs (shared and cached by checksum). - Environment-specific app image: Fast final
next buildper target environment (staging,production), running concurrently in CI on top of the cached base and dependency layers.
That keeps the slow OS and node_modules work shared and build-once, while still letting Next.js precompile fast, optimized assets for each environment.