Self-Hosting Next.js 16 in Docker: Standalone Output, Shared Cache Handlers and Multi-Replica Gotchas
Table of Contents
About the Author

Ahmed Mahmoud
Author & Developer
Software engineer passionate about web development and user experience design.
Founder of Devya · eng-ahmed.com ↗Headline: A self-hosted Next.js 16 app belongs in a Docker image built from output: "standalone", with public and .next/static copied in and HOSTNAME=0.0.0.0 set. One container works with zero extra configuration; a second replica needs a shared Server Functions encryption key, a deploymentId and shared cache handlers, because Next.js caches and invalidates per process by default.
Not every app we ship at Devya runs on Vercel. Some run on a VPS next to a NestJS API and a Postgres database, and there our team deploys Next.js as a Docker container behind nginx. The first container is easy. The trouble starts with the second replica: a page shows different content depending on which container answers, revalidateTag() seems to work only half the time, and a container health check fails while the site answers normally. Each problem comes from a default that assumes one process. This is the image we build and the settings that make several replicas behave like one app.
Key takeaways
• output: "standalone" makes next build emit .next/standalone: a minimal server.js plus only the traced files from node_modules, so the runtime image needs no dependency install.
• The standalone folder omits public and .next/static; copy both into the image or serve them from a CDN, or the HTML renders while every JavaScript chunk returns 404.
• Set HOSTNAME=0.0.0.0 in the image, because Docker sets HOSTNAME to the container ID and server.js binds to whatever that variable says.
• Next.js 16 has two cache-handler settings: cacheHandler (singular) stores ISR pages and route handler responses, and cacheHandlers (plural) backs 'use cache' and 'use cache: remote'. Both default to storage inside one process.
• revalidateTag() invalidates only the instance that ran it unless a shared cache handler writes the invalidation to shared storage such as Redis and every instance reads it back in refreshTags().
What does output: "standalone" actually produce?
Standalone output is a Next.js build mode that copies the production server and only the files it needs into .next/standalone. During next build, Next.js runs @vercel/nft, Vercel's Node.js file tracer, over every import, require and fs call, then copies just the traced files out of node_modules. The result starts with node server.js instead of next start. Enabling it is one line in next.config.ts: output: "standalone".
Two folders are left out on purpose: public and .next/static. The Next.js docs expect a CDN to serve them, and server.js serves them itself only after they are copied to standalone/public and standalone/.next/static. Missing the second copy gives a page whose HTML renders but never hydrates.
Monorepos need one more setting. File tracing stops at the Next.js project folder, so a workspace package outside it is missing from the output until outputFileTracingRoot points at the repository root. Files loaded through computed paths, such as locale JSON read with fs, go into outputFileTracingIncludes. Since Next.js 15, next start and standalone output use sharp for image optimization automatically, so we no longer install it by hand.
What does a production Dockerfile for Next.js 16 look like?
A production Next.js image needs three stages: install dependencies, build, and a runtime stage that contains only the standalone output. Our Dockerfile follows the official with-docker example, which uses the Debian-based node:24-slim image and the unprivileged node user.
The deps stage copies package.json and the lockfile and runs a frozen pnpm install. The builder stage copies node_modules and the source, receives DEPLOYMENT_VERSION as a build argument, and runs pnpm build with NEXT_SERVER_ACTIONS_ENCRYPTION_KEY read from a BuildKit secret mount, which keeps the key out of the image history. The runner stage sets NODE_ENV=production, PORT=3000 and HOSTNAME=0.0.0.0, copies .next/standalone, .next/static and public with ownership given to the node user, switches to USER node and starts with CMD ["node", "server.js"].
The slim image ships without curl, so our HEALTHCHECK runs a one-line node -e script that calls the fetch() built into Node.js 24 against http://127.0.0.1:3000/api/health. That route handler calls await connection() from next/server before returning Response.json({ status: "ok" }), so Next.js never prerenders it into a static file that answers 200 forever.
HOSTNAME=0.0.0.0 is the setting that fixes a failing health check. Docker sets HOSTNAME to the container ID, and Kubernetes sets it to the pod name. server.js reads HOSTNAME as its bind address, so without the override it listens only on the container's network address: traffic through the published port works, and a probe against 127.0.0.1 inside the container is refused.
The other environment trap is NEXT_PUBLIC_. Next.js inlines NEXT_PUBLIC_* values into the client bundle during next build, so an image built with staging values carries staging URLs into production. To promote one image through every environment, we keep the prefix for values that never change and read environment-specific values on the server after await connection(), passing them to Client Components as props. A .dockerignore with .next, node_modules, .git and .env* keeps local builds and secrets out of the build context.
What breaks when we run more than one Next.js replica?
A second Next.js replica behind a load balancer breaks three things: Server Function encryption, version-skew detection and caching. Each one defaults to state that lives inside one build or one process.
• Server Functions encryption key: the default is a new random key per build, which causes "Failed to find Server Action" errors when replicas come from different builds. The fix is NEXT_SERVER_ACTIONS_ENCRYPTION_KEY at build time, a base64 value of 16, 24 or 32 bytes.
• deploymentId: unset by default, so a rolling deploy pairs old clients with new servers and produces missing chunks and unknown action IDs. The fix is deploymentId: process.env.DEPLOYMENT_VERSION in next.config.ts.
• ISR and route handler cache: stored on disk plus 50 MB of memory per instance by default, so replicas serve different versions of the same page. The fix is a cacheHandler plus cacheMaxMemorySize: 0.
• 'use cache' entries: an in-memory LRU per process by default, so each replica fills and expires its own copy. The fix is a cacheHandlers.remote handler plus the 'use cache: remote' directive.
• revalidateTag(): invalidates the local instance only by default, so other replicas keep serving stale content. The fix is shared tag state that every instance reads in refreshTags().
Our next.config.ts for a multi-replica app sets output: "standalone", cacheComponents: true, deploymentId from the git SHA that CI passes in, cacheHandler pointing at an ISR handler file, cacheMaxMemorySize: 0 so no per-replica memory layer sits in front of Redis, and cacheHandlers with a remote entry pointing at a Redis-backed handler file.
The encryption key is the subtle one. Next.js embeds the build's key in the build output, so replicas started from one image already agree. The key breaks things when one release is built more than once, for example per host or per environment. We set it explicitly anyway, generated once with openssl rand -base64 32, so correctness never depends on how many times CI builds.
With deploymentId set, static asset URLs carry ?dpl=<deploymentId>, client navigations send an x-deployment-id header, and a mismatch triggers a full page load instead of a client-side navigation. Next.js also keeps a constant build ID when deploymentId is set, unless generateBuildId overrides it.
Which cache handler do we need: cacheHandler or cacheHandlers?
Next.js 16 has two independent cache-handler settings, and a multi-replica app that uses Cache Components and ISR usually needs both.
• cacheHandler (singular) backs ISR pages, route handler responses and optimized images, and implements get, set, revalidateTag and resetRequestCache.
• cacheHandlers (plural) backs 'use cache' through its default key, 'use cache: remote' through its remote key, and any named 'use cache: <name>' directive, and implements get, set, refreshTags, getExpiration and updateTags.
We leave 'use cache' on the default in-memory handler for cheap data where a short difference between replicas is acceptable, and we mark expensive or tag-invalidated data 'use cache: remote', which goes to Redis. A typical example is a getProduct(id) function that starts with the "use cache: remote" directive, calls cacheTag with product:<id> and cacheLife("hours"), and then queries the database.
Tag coordination is the part that makes revalidateTag() reach every replica. updateTags() runs on the instance that revalidated and writes a timestamp per tag to Redis, plus the tag name into a Redis set of revalidated tags. refreshTags() runs once per request, before the first read from that handler, and pulls those timestamps into the local replica with one SMEMBERS and one MGET. getExpiration() then returns the newest local timestamp for the requested tags.
That design treats every invalidation as immediate. revalidateTag(tag, "max") passes a second durations argument to updateTags(), and a complete handler uses it to serve stale entries while they refresh. The documented pitfalls are worth reading before writing get and set: the entry's value stream can be read only once, ISR entries contain Buffer and Map values that JSON.stringify() cannot round-trip, and Next.js never deletes from the store, so eviction by TTL is the handler's job. The Next.js Redis example README lists community handlers that already solve this, and we start from one of those before writing our own.
How do we keep streaming and graceful shutdown working in containers?
Streaming needs every proxy in front of Next.js to stop buffering, and graceful shutdown needs a stop timeout long enough for in-flight requests and after() callbacks.
• Buffering: nginx buffers proxied responses by default, which delivers Suspense fallbacks and the Partial Prerendering shell together with the slowest data. We set proxy_buffering off in the nginx location block; the Next.js docs show the same fix as an X-Accel-Buffering: no header from headers().
• Signals: the exec form CMD ["node", "server.js"] makes Node.js PID 1, so it receives SIGTERM directly; a shell-form CMD runs under /bin/sh, which does not forward it.
• Drain time: on SIGTERM, the Next.js server finishes in-flight requests and pending after() callbacks. Docker sends SIGKILL after 10 seconds by default, and the docs recommend a 10 to 30 second drain, so we set stop_grace_period: 30s in Compose.
Our nginx config defines an upstream with one server line per replica, proxies to it with proxy_http_version 1.1 and proxy_buffering off, and forwards Host, X-Forwarded-For and X-Forwarded-Proto so Next.js sees the real client.
FAQ
Q: Do we need output: "standalone" to run Next.js in Docker?
A: No. next start works with a full node_modules install, but standalone output copies only the traced files the server needs, which keeps the runtime image smaller and removes the dependency install from the final stage.
Q: Why does a standalone Next.js app render HTML but load no JavaScript?
A: The .next/standalone folder does not include .next/static or public. Copy .next/static to .next/standalone/.next/static and public to .next/standalone/public, or serve both from a CDN with assetPrefix.
Q: Can one Next.js Docker image be promoted from staging to production?
A: Yes, when environment-specific values are read on the server at request time. NEXT_PUBLIC_ variables are inlined during next build, so any per-environment value with that prefix forces one build per environment.
Q: Does revalidateTag() work across multiple Next.js containers?
A: Not by default. revalidateTag() invalidates only the instance that ran it; to reach every replica, a custom cache handler must write the invalidation to shared storage and each instance must read it back in refreshTags() before serving cached entries.
Further Reading
Full-Stack Engineering
Next.js after() in Production: Post-Response Work, the Static-Page Build-Time Trap, and When We Use a Queue Instead
Next.js after() moves analytics, audit logs, and cache work out of the response path, but it is not a job queue. Here is where we call after(), why it runs at build time on static pages, why cookies() throws inside it in Server Components, and when we use a durable queue instead.
Full-Stack Engineering
Refresh Token Rotation in NestJS and Next.js: Reuse Detection, Token Families, and the Parallel-Refresh Race — Field Notes
How we rotate refresh tokens on every use in our NestJS APIs, store them as hashed token families in Postgres, revoke a whole family when a used token comes back, and stop parallel requests and Next.js prefetches from logging users out.