In the previous lesson, the platform provided the certificate, balanced the load, stored the pages and knew how to roll back. On your own server, all of that is yours. In exchange, you get a fixed, predictable bill, the data wherever you decide, and nobody else's rules on how long a request lasts or how big a poster can be.

According to the documentation, a Docker container supports every Next.js feature. You're going to build a small image that runs without privileges, put NGINX in front of it without breaking streaming, deploy with a script that migrates, builds and swaps, shut down without cutting anyone off, and make backups that have actually been restored at some point. At the end you'll see what changes when there are two instances instead of one, which is where caching stops being automatic.

  1. Standalone output

With output: 'standalone', next build analyzes which files each route really uses and copies only those, with the necessary dependencies, to .next/standalone, along with a minimal server.js. The image doesn't need a full node_modules or npm.

// next.config.ts (addition)
// Only for the image: `next start` doesn't work with this output, and the tests use it (10-04)
output: process.env.STANDALONE_OUTPUT === '1' ? 'standalone' : undefined,

Three details from the documentation that shape the Dockerfile:

  • public/ and .next/static aren't copied. They're assumed to be served by a CDN; if there isn't one, you copy them by hand and server.js serves them.
  • server.js reads PORT and HOSTNAME. Docker sets HOSTNAME to the container's name, and the server would only listen on that interface: you have to set HOSTNAME=0.0.0.0.
  • It copies .env and .env.production if they exist at build time, and uses them as defaults. Not the others (.env.local…). The right thing is for none of them to reach the image, and for everything to come from the environment at startup.

  1. The image

# .dockerignore (the essentials)
.git
node_modules
.next
.env*
!.env.example
data/
playwright/
test-results/
secrets/
backups/
# Dockerfile
# syntax=docker/dockerfile:1
FROM node:24-slim AS base
WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED=1

FROM base AS deps
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --no-audit --no-fund

# Single-use image for applying migrations
FROM deps AS migrator
COPY drizzle.config.ts ./
COPY drizzle ./drizzle
COPY lib ./lib
USER node
CMD ["npx", "drizzle-kit", "migrate"]

FROM deps AS build
COPY . .
ARG NEXT_PUBLIC_SITE_URL
ARG ALLOW_INDEXING=""
ARG NEXT_DEPLOYMENT_ID
ENV NEXT_PUBLIC_SITE_URL=$NEXT_PUBLIC_SITE_URL \
    ALLOW_INDEXING=$ALLOW_INDEXING \
    NEXT_DEPLOYMENT_ID=$NEXT_DEPLOYMENT_ID \
    STANDALONE_OUTPUT=1
RUN --mount=type=secret,id=database_url,env=DATABASE_URL,required=true \
    --mount=type=secret,id=actions_key,env=NEXT_SERVER_ACTIONS_ENCRYPTION_KEY,required=true \
    --mount=type=cache,target=/app/.next/cache \
    npm run build

FROM base AS runtime
ENV NODE_ENV=production PORT=3000 HOSTNAME=0.0.0.0
COPY --from=build --chown=node:node /app/.next/standalone ./
COPY --from=build --chown=node:node /app/.next/static ./.next/static
COPY --from=build --chown=node:node /app/public ./public
COPY --chown=node:node scripts/task.mjs ./scripts/
RUN mkdir -p /data/files && chown node:node /data/files
USER node
EXPOSE 3000
CMD ["node", "server.js"]

Every decision has its reason:

  • Stages. The final one starts from the base image and only receives what's copied. The build tools, the source code and the development dependencies stay in the intermediate ones.
  • node:24-slim and not alpine. The slim variant uses the usual C library (glibc), which sharp's binaries are published for; the other uses musl and forces you to keep an eye on whether they exist. The Next.js documentation warns that sharp on glibc may need memory tuning: check that section of its installation guide before accepting the memory usage. Pin the exact version, for example with the image digest, and update it on purpose (11-06).
  • The node user, without privileges. If someone manages to run code, they do so without being able to touch the container's system. That's why the files folder is created and handed over before switching users.
  • Build secrets as secret, never as ARG. A build argument stays in the image history; a mounted secret doesn't. The env= option requires Dockerfile syntax 1.10 or later, which the first line guarantees.
  • NEXT_SERVER_ACTIONS_ENCRYPTION_KEY ends up inside the output anyway, as we warned in 08-06: Next.js embeds it in the output. The image contains a secret. Don't publish it to a public registry, and treat anyone who can download it as someone who can read the secret.
  • DATABASE_URL at build time because the shells are generated with data (05-02). A read-only role is used (section 4).
  • Google Fonts are downloaded at build time (09-02). If your build server has no internet access, switch to next/font/local with the files in the repository.
  • The .next/cache cache speeds up later builds and never reaches the image.
  • scripts/task.mjs, ten lines long, calls a task from inside the container (section 5).

  1. The services

# compose.production.yaml
name: agendaviva

services:
  db:
    image: postgres:18
    restart: unless-stopped
    environment:
      POSTGRES_USER: agendaviva
      POSTGRES_DB: agendaviva
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets: [db_password]
    volumes: [db-data:/var/lib/postgresql]
    ports: ['127.0.0.1:5432:5432'] # Only for building from the machine itself
    shm_size: 256mb
    healthcheck:
      test: ['CMD-SHELL', 'pg_isready -U agendaviva']
      interval: 5s
      retries: 10

  migrate:
    image: agendaviva-migrator:${VERSION:?VERSION is missing}
    profiles: [tools] # Only with docker compose run
    env_file: .env.prod
    depends_on: { db: { condition: service_healthy } }

  web:
    image: agendaviva:${VERSION:?VERSION is missing}
    restart: unless-stopped
    init: true
    env_file: .env.prod
    environment:
      FILES_DIR: /data/files
      INTERNAL_URL: http://127.0.0.1:3000
      TRUSTED_PROXIES: '1'
    volumes: [files:/data/files]
    depends_on: { db: { condition: service_healthy } }
    stop_grace_period: 30s
    mem_limit: 1g
    cap_drop: [ALL]
    security_opt: ['no-new-privileges:true']
    healthcheck:
      test: ['CMD', 'node', '-e', "fetch('http://127.0.0.1:3000/api/health').then((r) => process.exit(r.ok ? 0 : 1), () => process.exit(1))"]
      interval: 15s
      timeout: 3s
      start_period: 20s

  nginx:
    image: nginx:1.30-alpine
    restart: unless-stopped
    ports: ['80:80', '443:443']
    volumes:
      - ./nginx/agendaviva.conf:/etc/nginx/conf.d/default.conf:ro
      - ./nginx/maintenance.html:/usr/share/nginx/html/maintenance.html:ro
      - /etc/letsencrypt:/etc/letsencrypt:ro
      - certbot:/var/www/certbot:ro
    depends_on: [web]

secrets:
  db_password: { file: ./secrets/db_password }

volumes:
  db-data:
  files:
  certbot:
  • PostgreSQL isn't exposed to the network. The port only listens on the server's 127.0.0.1, so the deployment script can build against it; the containers talk to each other over the Compose internal network, using the name db.
  • .env.prod lives on the server, with 600 permissions, outside the repository. It contains DATABASE_URL=postgresql://agendaviva:…@db:5432/agendaviva and the rest of the table from 11-04.
  • The files volume holds the posters. When it's created empty, Docker copies the contents and the owner of the image's folder: hence the chown in the Dockerfile.
  • INTERNAL_URL points at the process itself. The proxy's existence check (07-02) doesn't go out to the internet or through NGINX.
  • The health check uses node, because the image doesn't have curl, and queries /api/health: if the process doesn't answer, Docker marks it as unhealthy. It doesn't query the database, for the reasons explained in 10-05.
  • init: true puts a minimal process in front that forwards signals and reaps orphaned processes.
  • cap_drop and no-new-privileges strip the container of capabilities a web application doesn't need. Port 3000 doesn't require any.

3.1. NGINX

The self-hosting guide recommends a reverse proxy in front, rather than exposing Next.js: it absorbs malformed requests, slow connections, huge bodies and bursts. This is its configuration, with comments where it matters:

# nginx/agendaviva.conf
upstream agendaviva {
    server web:3000;
    keepalive 16;
    keepalive_timeout 4s; # Less than Node's 5 s: let NGINX close first
}

limit_req_zone $binary_remote_addr zone=pages:10m rate=20r/s;
limit_req_zone $binary_remote_addr zone=api:10m rate=5r/s;

server {
    listen 80;
    server_name agendaviva.example;
    location /.well-known/acme-challenge/ { root /var/www/certbot; }
    location / { return 301 https://$host$request_uri; }
}

server {
    listen 443 ssl;
    http2 on;
    server_name agendaviva.example;
    ssl_certificate     /etc/letsencrypt/live/agendaviva.example/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/agendaviva.example/privkey.pem;

    client_max_body_size 3m;   # The poster: 2 MB plus the rest of the form
    client_body_timeout 15s;   # Connections that send one byte a minute
    client_header_timeout 15s;

    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Host $host;          # Compared by the actions' protection (08-06)
    proxy_set_header X-Forwarded-Proto https;
    proxy_set_header X-Forwarded-For $remote_addr;    # Replaces, doesn't append
    proxy_read_timeout 130s;                          # A bit more than the largest maxDuration

    location /_next/static/ { proxy_pass http://agendaviva; }

    location /api/tasks/          { return 404; }     # Only from inside (section 5)
    location = /api/health/ready  { return 404; }

    location /api/ {
        limit_req zone=api burst=20 nodelay;
        proxy_buffering off;
        proxy_pass http://agendaviva;
    }

    location / {
        limit_req zone=pages burst=40 nodelay;
        proxy_buffering off; # The shell goes out as soon as it's ready, and each hole when it arrives (04-04)
        proxy_pass http://agendaviva;
    }

    error_page 502 504 /maintenance.html;
    location = /maintenance.html { root /usr/share/nginx/html; internal; }
}
  • Streaming. By default NGINX buffers the server's response. In 04-04 we saw the X-Accel-Buffering: no header, which the documentation suggests sending from next.config.ts; here we choose proxy_buffering off, which lets the infrastructure decide without touching the application. Either one works. Static files, with immutable names, keep the buffer: that way NGINX frees the connection to Next.js sooner.
  • The visitor's IP. With $remote_addr, the header contains only the address NGINX saw, and whatever the client sent disappears. TRUSTED_PROXIES=1 takes the last element, which is that one (08-02). If there were another load balancer in front of NGINX, it would be 2 and you'd use $proxy_add_x_forwarded_for.
  • Host and X-Forwarded-Host. Without them, Next.js would compare each action's Origin with web:3000, and they would all fail (08-06).
  • The 3 MB limit is the third one: NGINX's, the actions' (bodySizeLimit) and the Next.js proxy's (06-05). The smallest one wins, which is why this one sits above ours.
  • The rate limits are the ones 08-06 and 10-01 left "for the load balancer": public reads, metrics and errors. Signed-in writes are already limited per person in PostgreSQL. With many visitors behind the same address (a school, a mobile network) a per-IP rate is unfair, so it's set generously.
  • keepalive_timeout 4s. If Node closed an idle connection just as NGINX was reusing it, the visitor would get a 502. The next start documentation explains the same problem with load balancers.
  • maintenance.html is served when Next.js doesn't answer, for example during the seconds of a deployment. The 503 from MAINTENANCE_MODE comes from the application and gets through as is.

The certificates are obtained by certbot with the .well-known folder method; their periodic renewal and the NGINX reload (nginx -s reload) go in the server's scheduler. Check that they renew before the first one expires.

  1. Deploying

The build needs the database and the new schema, so the deployment is done on the server itself, with a script that always does the same thing in the same order:

#!/usr/bin/env bash
# scripts/deploy.sh <git tag> — on the server, in /srv/agendaviva
set -euo pipefail
VERSION="$1"
export VERSION

git fetch --tags --quiet
git checkout --quiet --detach "$VERSION"

# 1. Back up before changing anything
./scripts/backup-db.sh

# 2. Migrate (compatible with the version still running: 11-04)
docker build --target migrator -t "agendaviva-migrator:$VERSION" .
docker compose -f compose.production.yaml run --rm migrate

# 3. Build against the real data, with a read-only role
docker build --network host \
  --secret id=database_url,src=secrets/build_db_url \
  --secret id=actions_key,src=secrets/actions_key \
  --build-arg NEXT_PUBLIC_SITE_URL=https://agendaviva.example \
  --build-arg ALLOW_INDEXING=1 \
  --build-arg NEXT_DEPLOYMENT_ID="$VERSION" \
  -t "agendaviva:$VERSION" .

# 4. Swap
docker compose -f compose.production.yaml up -d --no-deps web

# 5. Wait until it's healthy; if not, go back to the previous one
for _ in $(seq 1 30); do
  status=$(docker inspect -f '{{.State.Health.Status}}' "$(docker compose -f compose.production.yaml ps -q web)")
  if [ "$status" = healthy ]; then
    echo "VERSION=$VERSION" > .env # Compose reads it for the tasks and the backups
    exit 0
  fi
  sleep 2
done
echo "Version $VERSION won't start: roll back with deploy-previous.sh" >&2
exit 1
  • --network host lets the build reach 127.0.0.1:5432. With Docker's default build driver it doesn't need anything else; with others it may require explicit permissions.
  • The build role only has SELECT: create role agendaviva_readonly login password '…'; grant select on all tables in schema public to agendaviva_readonly;. Building doesn't write, and if it ever tried to, it must fail.
  • NEXT_DEPLOYMENT_ID is the tag. It's used to detect version skew (11-04) and is part of the 'use cache' key.
  • Images carry the git tag and not latest. Rolling back means starting the previous one: VERSION=v1.0.3 docker compose -f compose.production.yaml up -d --no-deps web, and writing that version to .env, the file Compose takes VERSION from when the command doesn't provide it, as in the tasks and the backups. That .env belongs to the server and only contains the version; the secrets are in .env.prod. Migrations aren't undone, and there's no need if they were written to be compatible. Keep the last five images and delete the rest.
  • There are a few seconds without service: Compose stops the old container before starting the new one, and NGINX shows the maintenance page. With a single instance, that's the price accepted in decision 11 of 11-01. Avoiding it takes two (section 7).

A detail that gets forgotten: the new image starts with the shells from its build and with nothing in the memory cache. The first visits recompute. If the deployment coincides with peak traffic, it shows.

  1. Tasks, shutdown and health checks

// scripts/task.mjs — inside the container: node scripts/task.mjs send-notifications
const [name = ''] = process.argv.slice(2)
if (!/^[a-z-]+$/.test(name)) {
  console.error('Usage: node scripts/task.mjs <task>')
  process.exit(2)
}

const response = await fetch(`http://127.0.0.1:3000/api/tasks/${name}`, {
  method: 'POST',
  headers: { Authorization: `Bearer ${process.env.TASKS_KEY}` },
  signal: AbortSignal.timeout(150_000),
})
console.log(name, response.status, await response.text())
process.exit(response.ok ? 0 : 1)
# The server's crontab (crontab -e)
*/5 * * * * cd /srv/agendaviva && docker compose -f compose.production.yaml exec -T web node scripts/task.mjs send-notifications >> /var/log/agendaviva/tasks.log 2>&1
40 3 * * *  cd /srv/agendaviva && docker compose -f compose.production.yaml exec -T web node scripts/task.mjs clean-auth >> /var/log/agendaviva/tasks.log 2>&1
10 4 * * *  cd /srv/agendaviva && docker compose -f compose.production.yaml exec -T web node scripts/task.mjs clean-files >> /var/log/agendaviva/tasks.log 2>&1
30 2 * * *  cd /srv/agendaviva && ./scripts/backup-db.sh >> /var/log/agendaviva/backups.log 2>&1

The tasks are called from inside, and NGINX returns a 404 for /api/tasks/ from outside: even if the key leaked, there'd be no door. It's defense in depth, like the optimistic proxy check from 08-04. The system scheduler uses the server's time; set it to UTC and write the times with that in mind.

Shutdown. When the container is stopped, Docker sends SIGTERM and waits for stop_grace_period; then, SIGKILL. Next.js finishes in-flight requests and pending after work before exiting, and the documentation recommends allowing between 10 and 30 seconds (07-04). Docker's default is 10; that's why we set 30, which covers the mail retries. For the signal to arrive, the main process must be node: with CMD ["npm", "start"], npm would receive it. What's pending in the outbox isn't at risk, because it's in a table.

The health checks from 10-05 fit like this: /api/health for Docker (is the process still alive?) and /api/health/ready for an external service that calls every minute and raises the alarm (is it serving?). The latter is queried from the machine itself, or by opening its location only to the monitoring service's address.

Traces. If you want the 10-05 viewer in production, add a service with the OpenTelemetry collector and set OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4318 in web. The collector is also the place to filter out personal attributes before sending them anywhere.

  1. Backups

#!/usr/bin/env bash
# scripts/backup-db.sh
set -euo pipefail
cd /srv/agendaviva
STAMP=$(date -u +%Y%m%dT%H%MZ)
C="docker compose -f compose.production.yaml"

$C exec -T db pg_dump -U agendaviva --format=custom agendaviva > "backups/db-$STAMP.dump"
$C exec -T web tar -C /data -cf - files > "backups/files-$STAMP.tar"

# Encrypt and move off the machine: your tool and your destination go here
# Delete local backups older than 7 days
find backups -type f -mtime +7 -delete

A backup that has never been restored is a hope. Restoring, on another machine and every month, is the only proof:

docker compose exec -T db createdb -U agendaviva agendaviva_restored
docker compose exec -T db pg_restore -U agendaviva --no-owner -d agendaviva_restored < backups/db-20261202T0230Z.dump
docker compose exec -T db psql -U agendaviva -d agendaviva_restored -c 'select count(*) from bookings'
Question Answer for AgendaViva
How much can we lose? 24 hours (RPO from 11-01): a daily backup. For minutes, continuous archiving of the transaction log or a managed PostgreSQL
Where? Off the server and off the provider: if the account is lost, both are lost
Encrypted? Yes. They contain email addresses and password hashes
For how long? Whatever compliance says. Someone who asks for their data to be deleted will remain in the backups until they expire: you have to be able to explain that
What else? The posters, .env.prod, the secrets and the NGINX configuration, in a secrets manager. Without them, the database backup brings nothing back up
Who knows how to restore? More than one person, with a written script

The RTO drill from 11-01 is exactly that: an empty machine, the script and a stopwatch. The first time, something fails; better on a Tuesday morning than on a festival Saturday.

A note for the future: upgrading to a new major version of PostgreSQL isn't a matter of changing the image tag. The on-disk format changes, and you need to dump and restore, or use pg_upgrade. That gets rehearsed too.

  1. More than one instance

A single instance more than covers the traffic of a municipal events guide. You move to two for three reasons: deploying without downtime, surviving a process crash, or because the CPU can't keep up, which in Next.js usually starts with the image optimizer. Before doing it, this is the list of what stops being true:

Piece With one With two
Actions key One per build Both instances must come from the same image, or share NEXT_SERVER_ACTIONS_ENCRYPTION_KEY
Deployment identifier The same in both; during a rolling update, each version its own
Posters on disk One volume S3 storage (11-04) or a shared volume
'use cache' and updateTag Process memory Each has its own: an invalidation only reaches the one that made it
Revalidated shells (ISR) Container disk Each has its own
Sessions, rate limits, outbox PostgreSQL No change: they were already outside the process
Tasks One call One call, to either of the two: no change
Connections 10 20: review PostgreSQL's maximum
Image optimizer cache On disk Duplicated; you accept it, or use a separate service with loaderFile (09-02)

The two cache rows are the important ones. Without doing anything, the application works, but whoever publishes an event sees it on the instance that handled their action, and the other one ignores it until its copy expires. The cacheLife times bound the lag (05-04), and for an events guide that could be acceptable. If not, both caches have to be shared: the 'use cache' one with cacheHandlers and the pages one with cacheHandler, singular.

// cache-handlers/redis.js — shared 'use cache' (npm install redis)
const { createClient } = require('redis')
const { PHASE_PRODUCTION_BUILD } = require('next/constants')

const ENTRY = 'agendaviva:cache:'
const TAG = 'agendaviva:tag:'
const TAG_TTL = 8 * 24 * 60 * 60 // More than the largest expire we use: one week

const client = createClient({ url: process.env.REDIS_URL, disableOfflineQueue: true })
client.on('error', () => {}) // Without a handler, a Redis outage would end the process
const connection =
  process.env.NEXT_PHASE === PHASE_PRODUCTION_BUILD ? Promise.resolve() : client.connect().catch(() => {})

async function redis() {
  await Promise.race([connection, new Promise((done) => setTimeout(done, 1000).unref())])
  return client.isReady ? client : null
}

async function tagMarks(r, tags) {
  if (tags.length === 0) return []
  const values = await r.mGet(tags.map((tag) => TAG + tag))
  return values.map((value) => (value ? JSON.parse(value) : {}))
}

module.exports = {
  async get(key) {
    try {
      const r = await redis()
      const text = r && (await r.get(ENTRY + key))
      if (!text) return undefined

      const entry = JSON.parse(text)
      let revalidate = entry.revalidate
      for (const { stale = 0, expired = 0 } of await tagMarks(r, entry.tags)) {
        if (expired > entry.timestamp && expired <= Date.now()) return undefined
        if (stale > entry.timestamp) revalidate = -1 // Serve it and revalidate in the background
      }
      const bytes = Buffer.from(entry.value, 'base64')
      const value = new ReadableStream({ start: (c) => { c.enqueue(bytes); c.close() } })
      return { ...entry, revalidate, value }
    } catch {
      return undefined // A cache failure isn't a page failure
    }
  },

  async set(key, pending) {
    const entry = await pending
    const bytes = Buffer.from(await new Response(entry.value).arrayBuffer()) // It's read once
    try {
      const r = await redis()
      if (!r) return
      const ttl = Number.isFinite(entry.expire)
        ? { expiration: { type: 'EX', value: Math.max(1, Math.ceil(entry.expire)) } }
        : {}
      await r.set(ENTRY + key, JSON.stringify({ ...entry, value: bytes.toString('base64') }), ttl)
    } catch {}
  },

  async refreshTags() {}, // Every read asks Redis: there's no local state to sync

  async getExpiration(tags) {
    try {
      const r = await redis()
      if (!r) return Date.now() // When in doubt, better to recompute
      return Math.max(0, ...(await tagMarks(r, tags)).map(({ expired = 0 }) => expired))
    } catch {
      return Date.now()
    }
  },

  async updateTags(tags, durations) {
    const r = await redis()
    if (!r) throw new Error('Redis is unavailable: the invalidation has not been recorded')
    const now = Date.now()
    const previous = await tagMarks(r, tags)
    await Promise.all(
      tags.map((tag, i) => {
        const mark = durations // With a profile ('max'): stale now, served while it revalidates
          ? { ...previous[i], stale: now, ...(durations.expire !== undefined && { expired: now + durations.expire * 1000 }) }
          : { ...previous[i], expired: now } // updateTag: no longer served
        return r.set(TAG + tag, JSON.stringify(mark), { expiration: { type: 'EX', value: TAG_TTL } })
      }),
    )
  },
}
// next.config.ts (addition): decided at build time
...(process.env.SHARED_CACHE === '1' && {
  cacheHandlers: {
    default: require.resolve('./cache-handlers/redis.js'),
    remote: require.resolve('./cache-handlers/redis.js'),
  },
  cacheHandler: require.resolve('./cache-handlers/pages.js'),
  cacheMaxMemorySize: 0,
}),

The contract it implements is in the cacheHandlers reference, and it's worth reading in full before copying anything:

  • value is a single-use stream. It's consumed in set and a new one is created on every get.
  • updateTags without durations comes from updateTag: the entry isn't served again. With durations, it comes from revalidateTag(…, 'max'): it's served while it revalidates. It's the distinction from 05-04, now across machines.
  • get never throws. An exception isn't interpreted as a cache miss, but as a page error.
  • updateTags does throw if Redis isn't there. If it claimed to have invalidated without doing so, once Redis came back every instance would serve the old content. The official example makes the same decision.
  • It doesn't connect at build time. The prerendering entries travel in the output itself.
  • Neither Redis nor the network is free: every cache read is now a round trip. Measure it before and after.

cache-handlers/pages.js is the other interface, the one for pages: get, set, revalidateTag and resetRequestCache, with their own serialization traps (the entries contain Buffer and Map). Don't rewrite it: start from the cache-handler.js in the official cache-handler-redis example, which covers those cases, or from one of the community packages its documentation links to. Then check that redis and both files are inside .next/standalone; if dependency tracing didn't find them, include them with outputFileTracingIncludes.

With the shared cache, deploying without downtime means splitting the load between two services, web-a and web-b, in NGINX's upstream block, and updating them one at a time. During that window two versions coexist: the compatible migrations from 11-04 and the deployment identifier, which forces anyone browsing from the previous version to reload, stop being theory.

Common Mistakes and Tips

  • Running as root inside the container.
  • Passing secrets as ARG, or leaving .env in the build context.
  • Publishing the image, which contains the actions key.
  • Forgetting HOSTNAME=0.0.0.0.
  • CMD ["npm", "start"]: the shutdown signal doesn't reach Next.js.
  • Ten seconds of grace with twenty-second retries.
  • Leaving NGINX buffering on, or an X-Forwarded-For that appends whatever the client sent.
  • Not sending Host: every action fails.
  • Exposing PostgreSQL or the tasks to the internet.
  • Tagging latest and not knowing which version to go back to.
  • Backups on the same server, unencrypted or never restored.
  • Two instances without a shared cache, believing that updateTag reaches both.
  • A cache handler that throws in get, or that reuses the stream.

Exercises

Exercise 1: is it streaming?

After deploying, an event page takes three seconds to show and then appears all at once. Locally, with the same image, the shell comes out instantly. Put the checks in order, with the commands, from the inside out.

Solution

# 1. Inside the container, without NGINX
docker compose -f compose.production.yaml exec web node -e "
  const t = Date.now(); fetch('http://127.0.0.1:3000/events/jazz-night').then(async (r) => {
    for await (const chunk of r.body) console.log(Date.now() - t, 'ms', chunk.length) })"

# 2. From the server, through NGINX
node scripts/watch-response.mjs https://agendaviva.example/events/jazz-night

# 3. From outside, and with a browser: Network tab, response timings

If the first shows several spaced-out chunks and the second a single one at the end, the culprit is NGINX: proxy_buffering off is missing in that location, or compression is buffering. If the first already arrives all at once, the problem is in the application: something above the first <Suspense> is waiting, and there's no shell (05-01). If the first two are fine and the third isn't, there's another layer in front: a firewall or the provider's CDN.

Exercise 2: a half-finished deployment

The script stopped at step 3: the migration was applied and the build failed because the build database wasn't accepting connections. What state is the site in? What do you do?

Solution

The site is still on the previous version with the new schema. If the migration was compatible, everything works, and you repeat the deployment once the connection is fixed: applying migrations is idempotent, because the applied ones are recorded. If it was not compatible, the site may be failing right now; the quick way out isn't undoing the migration, but finishing the deployment of the version that uses it, or restoring the backup from step 1 if data was lost.

The lesson: the script makes the backup first, and schema compatibility is what turns a half-finished failure into a nuisance. It's right that set -e stops the script, and that the swap comes at the end, too.

Exercise 3: do we need two?

The city council asks for "high availability". With what you've seen, explain what AgendaViva would gain with two instances on the same machine, what it wouldn't gain, and what you'd propose given the RTO from 11-01.

Solution

With two instances on the same machine you gain deployments without downtime and survival of a process failure, such as a memory leak. You gain nothing against a failure of the machine, the disk, the network or PostgreSQL, which is still a single one. In exchange, Redis and two cache handlers arrive to be operated.

With an RTO of four hours, the honest proposal is: one instance, daily off-site backups, a restore script rehearsed on a clean machine and an external health check. If you want less downtime during deployments, two instances. If surviving the loss of the machine is required, you need another one somewhere else and a database with a replica, and that jump in cost is decided with numbers, not with the word "high".

Conclusion

Standalone output leaves an image with just what's needed, which runs without privileges and receives the secrets at build time without keeping them in its history, except for the actions key, which lives inside and forces you to treat the image as a secret. NGINX in front absorbs what shouldn't reach Next.js, passes on the correct IP and Host, and lets responses stream. Deploying is a script: backup, compatible migration, build with real data and a swap with a health check. Shutdown waits thirty seconds, tasks are called from inside, and a backup only counts if it's been restored. With two instances, the cache stops being local and has to be shared.

You now know how to deploy by hand, both ways. The last lesson makes sure you don't have to: a pipeline that checks every change and deploys on its own, and the upgrade routine that will keep AgendaViva healthy once the course is over. CI/CD, Upgrades and Next Steps.

© Copyright 2026. All rights reserved