Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 72 ยท Deployment and Production

Self-Hosting and Docker

Run Next.js on your own servers: standalone output, a multi-stage Dockerfile, a reverse proxy, shared cache handlers for several instances, ISR and the image optimizer.

Self-hosting means you run the Next.js server yourself instead of handing the build to a platform. People do it for cost control, data location rules, existing infrastructure or simply because they want to understand what runs. A single Next.js app on a single machine is easy. The interesting questions start when you run several copies behind a load balancer, because Next.js keeps a cache and some secrets on each instance.

This lesson covers the standalone build output, a production Dockerfile, the settings your reverse proxy needs, what breaks when several instances share a job (caching, ISR, rolling deploys, Server Action keys) and what the image optimizer needs from the machine. The real commands, Dockerfile and nginx files are read-only because this site cannot run a container host. The two live examples are Node.js stand-ins that make the invisible parts visible: two cache instances that disagree, and a tracer that decides which files go into a standalone image. Their numbers are illustrative, not measurements.

One image, many copies

Standalone build A small folder with its own server.js.
Container image Build once, run the same image everywhere.
Load balancer Spreads requests across the copies.

Every copy must behave the same.

1 / 2

The standalone output

A normal next start needs the whole project folder: the .next build plus all of node_modules, development packages included, which can be hundreds of megabytes. The standalone output mode fixes this. Turn it on in the config:

TypeScript
// next.config.ts (read-only)
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  output: "standalone",
};

export default nextConfig;

After next build, Next.js traces which files your server code can actually reach (this is called output file tracing) and copies only those into .next/standalone, together with a minimal server.js. You start the app with plain Node.js:

Terminal
# read-only
node .next/standalone/server.js

The tracer does not copy two folders, because it assumes a CDN will serve them: public/ and .next/static/. If you serve everything from the Node process, copy them in next to server.js (public to ./public, .next/static to ./.next/static), as the Dockerfile below does. In a monorepo, where your app imports from sibling packages, set outputFileTracingRoot to the repository root so the tracer can see them.

The tracer follows the same idea as the stand-in below: start at the entry file, follow what it needs, and leave everything else behind. The package list and sizes are made up for the example; real numbers depend on your dependencies.

Node.js Tracing which packages a standalone image needs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Dev tools such as TypeScript, ESLint and the test runner are never reachable from the server entry, so they stay behind. react-dom and sharp come along because something that was traced needs them. The result is a much smaller image that starts faster and exposes less to attackers.

A production Dockerfile

A container image packages the standalone folder with the Node.js runtime, so the app runs the same on every machine. A multi-stage Dockerfile builds in one stage and copies only the result into a small final stage:

DOCKERFILE
# Dockerfile (read-only)
FROM node:24-alpine AS base

FROM base AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci

FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ARG NEXT_PUBLIC_SITE_URL
ENV NEXT_PUBLIC_SITE_URL=$NEXT_PUBLIC_SITE_URL
RUN npm run build

FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nextjs
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
HEALTHCHECK --interval=30s CMD wget -qO- http://127.0.0.1:3000/api/health || exit 1
CMD ["node", "server.js"]

Points worth understanding:

  • npm ci installs exactly what the lockfile says, so builds are repeatable. It sits in its own stage, and package.json is copied before the source code, so Docker reuses the cached dependency layer until the dependencies change.
  • NEXT_PUBLIC_* values are build arguments. They are baked into the browser code when npm run build runs, so you pass them with docker build --build-arg NEXT_PUBLIC_SITE_URL=https://shop.example .. An image built for staging carries staging's public values (Environment Variables and Secrets). Server-only secrets are different: pass them at run time with docker run -e or your orchestrator's secrets, never COPY an .env.local into the image.
  • ENV HOSTNAME=0.0.0.0 matters. Docker sets HOSTNAME to the container id, and the standalone server listens on whatever HOSTNAME says, so without this line it may listen on an address the outside world cannot reach.
  • The final stage runs as a non-root user, and contains no source code, no dev dependencies and no build tools.
  • A .dockerignore with node_modules, .next, .git and .env* keeps the build context small and stops local secrets from being copied into an image.

The health check calls a route you write yourself, for example a Route Handler that returns { ok: true } (Route Handlers). Keep it cheap: a health check that queries a slow database can restart healthy containers.

The reverse proxy

You rarely expose Node.js directly. A reverse proxy (nginx, Caddy, Traefik or a cloud load balancer) terminates HTTPS, spreads traffic and can serve static files. A minimal nginx location for a Next.js app:

NGINX
# read-only
server {
  listen 443 ssl;
  server_name shop.example;

  location / {
    proxy_pass http://app:3000;
    proxy_http_version 1.1;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
  }
}

What matters here:

  • Forward the original host and protocol. Next.js builds absolute URLs (redirects, metadata) from the Host and X-Forwarded-* headers. If the proxy hides them, redirects may point at http://app:3000.
  • Server Actions check origins. An action checks that the request's Origin matches the host. Behind a proxy that rewrites headers, actions can fail with an origin mismatch; fix the forwarded headers first, and if several public domains are involved list them in the allowedOrigins option for Server Actions in the config.
  • Streaming must not be buffered. Streamed pages (Streaming with Suspense) arrive in pieces. Next.js marks streaming responses so nginx does not buffer them; do not turn buffering back on for these routes.
  • Compression: next start compresses responses with gzip by default. If the proxy does that job, set compress: false in the config so the work is done once.
  • Hashed files under /_next/static/ never change, so a CDN or proxy can cache them for a very long time; Next.js already sends the right header.

Several instances: the cache problem

Now the real challenge. By default each Next.js instance keeps its caches in two places: memory and the local disk (.next/cache and prerendered pages in .next/server). That is fine for one instance. With three, every instance has its own cache, and nothing connects them.

Consider a product page cached with a tag. An admin edits the price, and the code calls revalidateTag("product") (Revalidating Data). The load balancer sends that request to one instance, which clears its cache. The other instances keep serving the old price until their time-based revalidation expires, if you set one, or forever if you did not. Visitors see different prices depending on which instance they hit. The stand-in simulates two instances behind a round-robin balancer, first with one cache each, then with a shared store.

Node.js Two instances, one revalidateTag call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In the first scenario, instance B keeps answering with 10 after the change, because the invalidation only reached instance A. With a shared store the single delete is visible to everyone, and all four later visits show 12.

Cache handlers

Next.js lets you replace its built-in cache with your own through a cache handler: a module that exports a class with methods to read, write and invalidate entries. The usual choice is a shared store such as Redis. A read-only sketch of the configuration and the shape of the class:

TypeScript
// next.config.ts (read-only)
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  cacheHandler: require.resolve("./cache-handler.js"),
  cacheMaxMemorySize: 0, // disable the per-instance memory cache
};

export default nextConfig;
JavaScript
// cache-handler.js (read-only sketch)
module.exports = class CacheHandler {
  constructor(options) {
    this.options = options;
  }
  async get(key) {
    // read the entry for this key from Redis, or return null
  }
  async set(key, data, ctx) {
    // write the entry to Redis, remembering ctx.tags for later invalidation
  }
  async revalidateTag(tags) {
    // delete every entry that carries one of these tags
  }
  resetRequestCache() {}
};

Setting cacheMaxMemorySize to 0 turns off the in-memory layer, since a memory copy on each instance would bring back the disagreement. Caching with the "use cache" directive (The use cache Directive and Cache Components) is configured with a separate option, cacheHandlers (plural), which accepts named handlers. In practice most teams use a maintained package that implements these interfaces for Redis instead of writing their own; check which Next.js versions it supports before you depend on it.

ISR on several servers

Incremental static regeneration (Revalidating Data) rewrites a prerendered page after it goes stale. On one server, the new page is saved to disk and later visitors get it. On several servers without a shared cache, each instance regenerates and stores its own copy at its own pace, a regenerated page is lost when the container is replaced (container filesystems are temporary), and an on-demand revalidation reaches one instance only. A shared cache handler solves all three. If you cannot add one, keep pages that need fresh data fully dynamic and cache at the CDN with short s-maxage headers instead.

Rolling deploys

Replacing instances one at a time raises three more problems.

  1. Server Action keys. Next.js encrypts the data that Server Actions send between page and server. Each build generates a key, so if two builds (or two separately built images) serve traffic at once, an action posted from a page rendered by one cannot be decoded by the other. Set one stable key for all instances with the NEXT_SERVER_ACTIONS_ENCRYPTION_KEY environment variable: a base64-encoded 32-byte value, for example from openssl rand -base64 32, supplied at build time and at run time.
  2. Version skew. During a deploy, a visitor may load HTML from the old version, then request JavaScript files that the new version no longer has. Keep old static assets available for a while (a CDN in front, with the assetPrefix pointing at it, does this naturally), and use the deploymentId config option so the framework can detect a client built for another deployment and reload it.
  3. Build identity. If you build separately on each server, give every build the same id with generateBuildId (for example the Git commit hash). The better fix is to build once in CI and run the same image everywhere, which is what the Dockerfile above is for.

The image optimizer's needs

next/image (Image Optimization with next/image) resizes and converts pictures on the server the first time they are requested, then caches the result on disk. That has consequences for self-hosting:

  • It uses the sharp library for speed. Recent Next.js versions use it automatically when available; to be certain on your base image, add sharp as a dependency and check the container logs for warnings on first start.
  • Resizing uses CPU and memory in bursts. Size the container for it, or you will see slow first views of every image.
  • The optimized files are written to .next/cache/images, which must be writable. In a read-only container, mount a volume or a temporary directory there. Each instance has its own copy, so the same image may be processed once per instance.
  • Remote images must be allowed in images.remotePatterns, or the optimizer rejects them. This is also a security control: it stops strangers from using your server as a free image resizer.
  • If the load worries you, move the work elsewhere: a custom loader sends image URLs to an image CDN, and images.unoptimized turns the optimizer off.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does output: "standalone" produce?

    Standalone traces which files are reachable from the server and copies just those, so you can run node server.js without the whole node_modules folder.
  2. 2. Why does the Dockerfile set ENV HOSTNAME=0.0.0.0?

    The standalone server binds to the HOSTNAME value. Setting it to 0.0.0.0 makes it listen on all interfaces, so the port mapping works.
  3. 3. Three instances run behind a load balancer with default caching. revalidateTag runs on one of them. What happens?

    Each instance has its own cache by default. To share invalidation, use a shared cache handler such as one backed by Redis.
  4. 4. When must NEXT_PUBLIC_SITE_URL be provided to a Docker-based deployment?

    NEXT_PUBLIC_ values are inlined during next build, so pass them as build arguments. Server-only secrets are the ones you supply at run time.
  5. 5. Why set one NEXT_SERVER_ACTIONS_ENCRYPTION_KEY for every instance?

    Action data is encrypted with a per-build key unless you provide one. A stable shared key lets any instance decode actions posted from pages rendered by another.

Summary

  • output: "standalone" traces the files the server needs into .next/standalone; copy public and .next/static yourself or serve them from a CDN.
  • A multi-stage Dockerfile builds once, passes NEXT_PUBLIC_ values as build arguments, sets HOSTNAME=0.0.0.0, runs as a non-root user and keeps secrets out of the image.
  • Behind a reverse proxy, forward Host and X-Forwarded-*, do not buffer streamed responses, and compress in only one place.
  • Default caches are per instance; use a shared cache handler (and cacheMaxMemorySize: 0) so revalidateTag and ISR work across several servers.
  • For rolling deploys, share one Server Actions encryption key, keep old assets available, and build once in CI.
  • The image optimizer needs sharp, CPU and a writable cache folder, or it can be replaced by a custom loader.

Next: Observability and Scaling