, 12 min read, by

Next.js Standalone in a Container Behind Traefik: HOSTNAME, Server Actions, Health Check

Three production instances measured: 221 to 239 MB image, of which roughly 64 to 79 MB is the application. Plus the Server Actions message behind the proxy and a Dockerfile on Node 24 Alpine.

Three of my Next.js applications run with output: 'standalone' in containers behind Traefik v3, two as monorepos. On 14 November 2026 I measured all three read-only (docker inspect, docker stats --no-stream, docker exec with printenv, du and netstat), with no restart and no build. The multi-stage basics are in my post on multi-stage Dockerfiles for Node and .NET.

What output: 'standalone' puts into the image

server.js, traced dependencies and two folders that are missing

With output: 'standalone', next build uses @vercel/nft to statically analyse all import, require and fs usage and copies into .next/standalone only what a page might load, including the required parts of node_modules, plus a minimal server.js in place of next start. According to the docs it deliberately leaves out two folders, because ideally a CDN serves them: public and .next/static. Without a CDN you copy both by hand:

cp -r public .next/standalone/ && cp -r .next/static .next/standalone/.next/
node .next/standalone/server.js

Three production instances, measured read-only

All values from 14 November 2026, linux/arm64: image sizes uncompressed from docker inspect, rounded to MB; /app from du -sh inside the container; memory from docker stats at idle, excluding file cache.

Instance A Instance B Instance C
Base image node:24-alpine node:24-alpine node:26-alpine
Node in the container v24.22.2 v24.22.1 v26.3.1
Layout monorepo monorepo single project
Image total 239 MB 221 MB 227 MB
Directory /app 75.1 MiB 61.3 MiB 64.2 MiB
RAM at idle 62.65 MiB 88.54 MiB 136.5 MiB
User node (UID 1000) node (UID 1000) nextjs (UID 100), created separately

For context, the locally present base tags: 162 MB (node:24-alpine, still with Node 24.18.0 there) and 174 MB (node:26-alpine), older than the current tags. So the larger part of each image is the base image of Node and Alpine, and the application in standalone format occupies 61 to 75 MiB in /app, roughly 64 to 79 MB. An exact split cannot be derived from this: docker inspect measures image layers, du the space used inside the container.

Dockerfile: where I deviate from the official with-docker example

The official example in examples/with-docker (Dockerfile last changed on 2 October 2026) builds in three stages on node:24.13.0-slim, uses the node user and has no HEALTHCHECK. I keep the structure, restrict it to npm (the example detects npm, yarn and pnpm from the lockfile) and change these points:

Official example My Dockerfile Reason
Base node:24.13.0-slim (Debian), pinned to a patch node:24-alpine as major tag, pinnable to 24.22.3-alpine3.24 two of three instances run this way
HEALTHCHECK none node -e fetch against 127.0.0.1:3000/healthz Traefik evaluates the health status
Compression Next.js (gzip) Traefik compress, compress: false in Next.js Brotli and Zstandard in the proxy
Build ID random per build from GIT_HASH fixed ID in case each environment is rebuilt

Node 24 on Alpine, although Node 26 is Active LTS

Since 28 October 2026 Node 26 is Active LTS, and Node 24 has been Maintenance LTS since 20 October 2026 with end of life on 30 April 2028. I stay on 24: two of three instances run on it, so does the official example, and next@16.4.6 only requires Node 20.9.0 or newer. The Hub tag lts-alpine now points to 26, so unpinned it switches major version; hence 24-alpine as a major tag instead of the patch pin from the example. node:24-alpine was last built on 11 November 2026 and contains Node 24.22.3 on Alpine 3.24.

Alpine instead of slim: the docker-node README puts node:alpine at "around 25% smaller than the Debian-based node:slim images". Alpine 3.24 is enough for Next.js because next@16.4.6 ships SWC as a musl build (@next/swc-linux-arm64-musl on my arm64 instances) and sharp@0.35.5 provides ARM64 prebuilts for musl 1.2.5 and newer; Alpine 3.24 has musl 1.2.6. The example README itself names the switch to Alpine as an option, provided your dependencies work with musl and are tested; in my case it is proven. For the sharp version after the October vulnerabilities, see my check matrix for Next.js 16.4.1.

The node user, permissions on .next and the health check

Two places in the example are not cosmetic: RUN mkdir .next followed by RUN chown node:node .next (merged into one line below) and --chown=node:node on every COPY of the runner stage. According to pull request #54870, the App Router attempts to write to .next/cache and .next/server at runtime; if .next belongs to root, the server warns with Failed to update prerender cache for <path> ... EACCES: permission denied. Instance C has been running healthy with a root-owned .next since June 2026; whether the warning sits in its log I have not checked.

I add the health check because, without allowEmptyServices (default false), Traefik's Docker provider according to the docs makes creating the load balancer depend on the health state; by my reading, an unhealthy container drops out. As the command I use node -e "fetch(...)", because fetch has been stable and global in Node since 21.0.0; instance A uses Busybox wget instead (/usr/bin/wget -> /bin/busybox). I target 127.0.0.1 because, in my experience, localhost in Alpine containers can resolve to ::1 first while the server only listens on IPv4. interval and retries are the Docker defaults 30s and 3; timeout 5s and start-period 30s are my choice, explained in my post on HEALTHCHECK and restart_policy.

The example README requires the example's .dockerignore in the project root alongside the Dockerfile. Without it, COPY . . in the builder stage also copies a local node_modules and .next and overwrites the dependencies just installed in the container. The minimum from the original:

# .dockerignore
node_modules/
.next/
.git/
.env
.env*.local
# syntax=docker/dockerfile:1
# Pinnable to 24.22.3-alpine3.24 (as of 15 Nov 2026)
ARG NODE_VERSION=24-alpine

FROM node:${NODE_VERSION} AS dependencies
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --no-audit --no-fund

FROM node:${NODE_VERSION} AS builder
WORKDIR /app
COPY --from=dependencies /app/node_modules ./node_modules
COPY . .
ENV NODE_ENV=production
ARG GIT_HASH
ENV GIT_HASH=${GIT_HASH}
RUN npm run build

FROM node:${NODE_VERSION} AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
COPY --from=builder --chown=node:node /app/public ./public
RUN mkdir .next && chown node:node .next
COPY --from=builder --chown=node:node /app/.next/standalone ./
COPY --from=builder --chown=node:node /app/.next/static ./.next/static
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
  CMD node -e "fetch('http://127.0.0.1:3000/healthz').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
CMD ["node", "server.js"]

I did not build it on the production server.

HOSTNAME and PORT: what Docker sets and what server.js reads

Why HOSTNAME=0.0.0.0 appears twice in my setup

The generated server.js reads process.env.PORT (otherwise 3000) and process.env.HOSTNAME (otherwise 0.0.0.0). Docker, however, automatically sets HOSTNAME in every Linux container to the container hostname, shown in the Docker docs as HOSTNAME=d2219b854598. Without a value of your own, server.js would therefore bind to the container ID. That is presumably why ENV HOSTNAME="0.0.0.0" is in the official example; the example does not explain it.

The Running containers page of the Docker docs (retrieved 15 November 2026) does not say whether an ENV in the image wins against Docker's automatic value. My measurement: in all three containers printenv HOSTNAME returns 0.0.0.0 while hostname prints the container ID, and netstat -tln shows 0.0.0.0:3000 LISTEN. For A and C the value comes from the image, for B from the Compose file. That is why I set HOSTNAME in environment: as well.

NEXT_PUBLIC_ gets baked in, server values do not

Variables prefixed with NEXT_PUBLIC_ are written into the JavaScript bundle during next build and cannot be changed in the finished image. Values read on the server are evaluated by Next.js at runtime during dynamic rendering, which the docs call the way to a single image for all environments. I set the build ID to the Git hash; according to the docs this is only needed when each environment is rebuilt. When deploymentId is set, the docs say Next.js uses a constant build ID unless generateBuildId is configured. I only set compress: false because Traefik compresses, otherwise the docs advise against disabling it.

// next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  output: "standalone",
  // || instead of ??: an empty GIT_HASH (ARG without a value) falls back to the default ID
  generateBuildId: async () => process.env.GIT_HASH || null,
  compress: false,
};

export default nextConfig;
// app/healthz/route.ts
export async function GET() {
  return new Response("ok");
}

Route Handlers are not cached by default.

Server Actions behind the proxy

The message in the log and its cause

On every Server Action, Next.js compares the host from the browser's Origin header with its own host, taken from x-forwarded-host or host. If the two differ, action-handler.ts in version 16.4.6 writes to the log:

`x-forwarded-host` header with value `<proxy-host>` does not match `origin` header with value `<browser-host>` from a forwarded Server Actions request. Aborting the action.

Without x-forwarded-host in the request, the first part reads `host` header. The handler then rejects the request with the error Invalid Server Actions request., for fetch actions with status 500, otherwise as a thrown error; if only the Origin header is missing, it stays a warning.

The docs describe the comparison as CSRF protection; the trigger is a proxy that forwards its own host instead of the public one, transferred to the example here: the browser sends app.example.com, the server sees nextapp:3000. Behind a reverse proxy, according to the docs, no entry is needed as long as the proxy forwards the public host in x-forwarded-host; otherwise add the public host, with port if the URL has one. In Next.js 16.4.6 the option still lives under experimental:

experimental: {
  serverActions: {
    allowedOrigins: ["app.example.com", "*.example.com"],
  },
},

"Failed to find Server Action" after a deploy

A second message, Failed to find Server Action "<id>". This request might be from an older or newer deployment., occurs when client and server come from different builds, typically a stale browser tab after a deploy. With several instances there is a second cause: Next.js encrypts closure variables of Server Functions with a key generated anew for each build. The remedy is NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, a base64-encoded AES key of 16, 24 or 32 bytes, generated for example with openssl rand -base64 32 and set at build time.

Key and cache handler solve different problems: the fixed key lets all instances decrypt the same values, the handler is needed for a shared cache. With one instance per application, neither comes up, unless the cache is meant to survive a restart. Against the stale browser tab, deploymentId (NEXT_DEPLOYMENT_ID) at build time helps: on a mismatch the client does a full page reload.

Traefik labels and the Compose file

Request path and Compose file

+---------+  https://app.example.com  +------------------+  http://web:3000  +------------------+
| Browser | ------------------------> | Traefik v3.7.19  | ----------------> | node server.js   |
|         | <------------------------ | websecure + ACME | <---------------- | HOSTNAME=0.0.0.0 |
+---------+  Brotli via compress      +------------------+ Host unchanged    +------------------+
services:
  web:
    image: ghcr.io/example/nextapp:${GIT_HASH}
    build:
      context: .
      args:
        GIT_HASH: ${GIT_HASH}
    restart: unless-stopped
    environment:
      NODE_ENV: production
      PORT: "3000"
      HOSTNAME: "0.0.0.0"
    networks:
      - traefik
    labels:
      - traefik.enable=true
      - traefik.docker.network=traefik
      - traefik.http.routers.nextapp.rule=Host(`app.example.com`)
      - traefik.http.routers.nextapp.entrypoints=websecure
      - traefik.http.routers.nextapp.tls=true
      - traefik.http.routers.nextapp.tls.certresolver=letsencrypt
      - traefik.http.services.nextapp.loadbalancer.server.port=3000
      - traefik.http.middlewares.nextapp-compress.compress=true
      - traefik.http.middlewares.nextapp-compress.compress.encodings=br,zstd,gzip
      - traefik.http.routers.nextapp.middlewares=nextapp-compress

networks:
  traefik:
    external: true

What the individual labels do

Traefik runs in my setup with providers.docker.exposedByDefault=false, hence the traefik.enable=true; the entrypoint is called websecure in my static configuration, and letsencrypt is a placeholder for your resolver name. With more than one network, Traefik needs the network name, globally via providers.docker.network or, as here, via traefik.docker.network; otherwise it picks one at random according to the docs. I always set loadbalancer.server.port=3000, otherwise Traefik takes the first exposed port; the wrong one shows up as HTTP/502 Gateway Error. The compress middleware supports Gzip, Brotli and Zstandard, but with equally weighted Accept-Encoding values it picks by the order of its encodings option (default gzip, br, zstd); without the encodings=br,zstd,gzip label you only swap Gzip from Next.js for Gzip from Traefik. Because, according to the docs, the middleware only compresses responses without a Content-Encoding already set (and only from minResponseBodyBytes, default 1024 bytes), compress: false sits above. If you use Caddy instead of Traefik, the differences are in my comparison of Caddy and Traefik. If you would rather not run a setup like this yourself: exactly that is what I take on in IT support.

Questions from operations

What changes in a monorepo?

The tracing root is the project directory by default; with next build apps/web everything outside is left out. Set outputFileTracingRoot to the common parent directory, otherwise the build warns, in substance, that traced files outside of it are not included in the standalone output. My instances A and B start this way with node apps/web/server.js.

What happens with several replicas?

Each instance keeps its own cache, 50 MB in memory by default, and revalidateTag() only invalidates on the calling instance. Several replicas need a cacheHandler with external storage such as Redis and cacheMaxMemorySize: 0; so that tag invalidations reach all instances, the handler must, according to the self-hosting guide, sync the tag state from the shared storage. Add the shared encryption key from above.

How does the container stop cleanly?

The server finishes in-flight requests and after() callbacks when it receives SIGTERM or SIGINT; the docs recommend a drain period of 10 to 30 seconds. For that the signal has to arrive, so CMD in exec form as above. In the source, the process exits after SIGTERM with exit code 143.

Documentation I had open while writing

Official references

output: standalone, the self-hosting guide, the option serverActions.allowedOrigins and the with-docker example.

My next step

Build the Dockerfile with GIT_HASH in the GitHub Actions pipeline and bring A and B up to the current patch level.

Note: The articles on this blog are produced with the help of AI and are editorially reviewed before publication. Editorial responsibility lies with Emre Yurtbay (see the legal notice).

Let's talk

In a free initial consultation, you describe your situation to me. I will give you an initial assessment of how I can support you.

Request a free initial consultation