Self-hosting with Node.js and Docker

Advanced · 17 min

Run Next.js with next start or the standalone output, package it in a multi-stage Docker image, and handle the caches, env vars, and proxy settings.

Before thisBuild output and next buildDeploying to Vercel

leerob · 17 min

Self-hosting with Node.js and Docker

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by leerobReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • All Next.js features work on a plain Node.js server: next build, then next start. Nothing in the framework requires a particular platform.
  • output: 'standalone' traces the files the server needs and writes them to .next/standalone with a minimal server.js; you copy public and .next/static in yourself unless a CDN serves them.
  • A good Docker image is multi-stage: install, build, then a small runner stage that copies only the standalone output and runs node server.js as a non-root user.
  • Server environment variables are read at request time in dynamically rendered code, so one image can be promoted through environments; NEXT_PUBLIC_ values are baked in at build.
  • With more than one instance, the default on-disk cache is per instance, and you must set a shared cache handler, a shared Server Functions encryption key, and a deployment ID.

The server is not the hard part

Hosting a Next.js app yourself sounds like it should be an ordeal, because platforms spend so much effort selling it as one. The docs say the minimum requirement is a Node.js server and nothing else: one next start process handles Server Components, ISR, Partial Prerendering, Cache Components, Server Actions, the proxy, and after(). What takes thought is everything around it: where files come from, where caches live, and what happens when there are two copies.

Plain Node.js

Make sure package.json has the scripts from the docs:

{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  }
}

Run npm run build, then npm run start. That server needs your node_modules next to it, because next start loads Next.js from there. Put a reverse proxy such as nginx in front. The docs recommend it so the proxy absorbs malformed requests, slow connections, payload limits, and rate limiting, leaving Next.js free to render.

The standalone output

Shipping all of node_modules is heavy. next build already traces which files each route needs using @vercel/nft, so you can ask it to write only those:

// next.config.ts
import type { NextConfig } from 'next'

const config: NextConfig = { output: 'standalone' }
export default config

On 16.4.6 the build produced .next/standalone containing server.js, a package.json, a traced node_modules (about 39 MB for a tiny app), and the .next server files. I ran it with PORT=3111 HOSTNAME=127.0.0.1 node server.js: it printed Ready, served /, and /blog/a (a generateStaticParams page) returned 200.

The standalone folder does not include public/ or .next/static. The docs say these should ideally come from a CDN, and give the copy commands if the server should serve them:

cp -r public .next/standalone/ && cp -r .next/static .next/standalone/.next/

In a monorepo, tracing starts at the project directory, so shared files outside it are missed. outputFileTracingRoot widens the root, and outputFileTracingIncludes or outputFileTracingExcludes fix specific routes.

A Docker image

Docker’s value here is repeatability. The docs point to the Next.js repository’s with-docker example, which builds in three stages. This is a trimmed version of it, assuming output: 'standalone' and an npm lockfile:

FROM node:24-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci

FROM node:24-slim AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NODE_ENV=production
RUN npm run build

FROM node:24-slim AS runner
WORKDIR /app
ENV NODE_ENV=production PORT=3000 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
CMD ["node", "server.js"]

Why the stages: the first caches dependency installs until the lockfile changes, the second compiles, and the last carries only what runs. The final image holds no source and no dev dependencies. It runs as the unprivileged node user, with .next writable so ISR can write regenerated pages. HOSTNAME=0.0.0.0 makes the server listen on every interface; without it, a server bound to localhost inside a container is unreachable from outside.

I did not have Docker available when writing this, so the Dockerfile is not built here. It is adapted from the official example, and I ran the standalone server it relies on directly.

Environment variables

By default variables exist only on the server. NEXT_PUBLIC_ ones are inlined into the client bundle at next build, so they are fixed per image. Server-side variables read during dynamic rendering are read at request time. The docs’ pattern is to call await connection() (or read cookies(), headers()) first, so the read happens per request and one image can be promoted from staging to production with different values. A page prerendered at build time has already baked in whatever value existed then, which is why static and dynamic rendering matters for configuration.

Caches and more than one instance

On one server with a persistent disk, ISR and the data cache work with no setup. The cache lives in memory (50 MB by default) and on local disk. Run several instances, or use disks that do not persist, and each has its own copy. The docs list what to configure:

  • A shared cache handler. cacheHandler in next.config for ISR and fetch caching, and cacheHandlers for 'use cache', backed by something every instance can reach, such as Redis or S3. Set cacheMaxMemorySize: 0 to disable the in-process copy. Tags must be shared too, so revalidateTag on one instance invalidates all of them.
  • A Server Functions encryption key. Closure variables sent to the client are encrypted with a key generated per build. Instances built separately must share one, set through NEXT_SERVER_ACTIONS_ENCRYPTION_KEY as a base64 AES key. Otherwise you get “Failed to find Server Action” errors.
  • A deploymentId. It lets Next.js detect version skew during rolling deployments and fall back to a full page load instead of a broken client-side navigation. The docs say to use generateBuildId if you rebuild per environment and need identical build IDs.

Revalidation and cache tags explains the tag model these settings coordinate.

Streaming, images, and shutdown

  • Streaming through nginx. Buffering turns a stream into one slow response. Set X-Accel-Buffering: no with a headers() entry, and make sure every hop supports chunked transfer or HTTP/2 streaming. Partial Prerendering loses its time-to-first-byte benefit without it.
  • Images. next/image optimization works with zero configuration under next start. sharp is an optional dependency of Next.js, and on glibc-based Linux the docs say you may need extra configuration to avoid excessive memory use.
  • Shutdown. Send SIGINT or SIGTERM and wait. The server finishes in-flight requests and runs pending after() callbacks, so allow a drain period; the docs suggest 10 to 30 seconds.

Static exports are the case where you drop the server entirely.

What the video covers

Lee Robinson’s video, which the self-hosting docs themselves link, deploys Next.js, Postgres, and Nginx to a VPS with Docker. From its chapters, the embedded clip (0:00 to 17:24) covers a demo app, setting up the Linux server, VPS versus dedicated servers, vertical versus horizontal scaling, and deploying to the VPS. The full 45 minutes continues with data fetching, image optimization, streaming, Postgres, ISR and caching, middleware, environment variables, startup code, a cron job hitting a Route Handler, rate limiting, and the tradeoffs against managed services. Those later chapters line up with sections above, so watching on is worthwhile.

Transcripts were unavailable, so I can say what the chapters list, not how the narration treats it. It dates from October 2024, before Next.js 16, so middleware is now proxy, and I could not confirm whether its image uses the standalone output. The prose above is checked against 16. The runner-ups are ByteGrad’s Dockerfile-to-VPS video (which has sponsored segments and a paid course plug) and a short conference talk on the adapter API.

Where this fits

You have the three outputs of a build: platform, server, or container. One more output removes the server altogether: static exports.

Check yourself

  1. 01What does output: 'standalone' change, and what does it not copy for you?

    It makes next build write a self-contained folder to .next/standalone, containing a traced subset of node_modules and a minimal server.js you can run with node. It does not copy public or .next/static by default; copy them into standalone/public and standalone/.next/static yourself if the server, not a CDN, should serve them.

  2. 02Why does the official Dockerfile set HOSTNAME to 0.0.0.0?

    The standalone server reads PORT and HOSTNAME to decide where to listen. In a container it has to listen on all interfaces to be reachable from outside, so the image sets HOSTNAME to 0.0.0.0 and PORT to 3000.

  3. 03You run three containers behind a load balancer. What breaks by default?

    The ISR and data cache is stored per instance on local disk, so revalidation on one instance does not reach the others, and Server Functions encrypt closures with a per-build key, so a function sent from one build can fail to decrypt on another. Configure a shared cacheHandler, set NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, and set a deploymentId.

  4. 04How do you stop an nginx proxy from breaking streaming responses?

    Disable response buffering for the app. The docs show setting an X-Accel-Buffering: no header from next.config headers(), and note that load balancers and any other proxy in the path must also pass chunked responses through.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark