Deployment
How to deploy a Next.js app with PostgreSQL using Docker Compose
By Anupa Dinuranga, FounderUpdated 10 min read
Do you need a server and a database?
This setup is for Next.js apps that run code when a request arrives: pages rendered per request, route handlers that accept POST requests, Server Actions behind forms, middleware for auth, and a database those features read and write. A typical example is a dashboard or a small SaaS where users log in and see their own data.
If your app has none of that, you don't need any of this page. A static export (output: "export") is cheaper and has almost nothing to maintain; our guide on the three ways to host Next.js shows how to tell the difference and how to deploy each option.
What you end up with by the end of this guide is one server running three containers:
- web: your Next.js app, built with standalone output
- db: PostgreSQL, with its data in a named volume and no public port
- caddy: a reverse proxy that gets HTTPS certificates on its own and is the only container listening on ports 80 and 443
You need Docker Engine with the Compose v2 plugin (docker compose, not the old docker-compose), installed from the official Docker repository. The examples use Prisma for migrations; if you use Drizzle, the equivalent command is noted where it matters.
Step 1: Build a standalone Docker image
Set output: "standalone" so next build writes a minimal server.js plus only the node_modules files the server needs into .next/standalone.
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "standalone",
};
export default nextConfig;The Dockerfile has four stages. The last two are the ones you run: runner is the small production image, and migrator is a separate image for database migrations (more on why in Step 3).
FROM node:22-alpine AS base
# 1. Install all dependencies (the build needs devDependencies)
FROM base AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
# 2. Build
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NEXT_TELEMETRY_DISABLED=1
# Public values are baked into the browser bundle here
ARG NEXT_PUBLIC_SITE_URL
ENV NEXT_PUBLIC_SITE_URL=$NEXT_PUBLIC_SITE_URL
RUN npx prisma generate
RUN npm run build
# 3. Migrations image: full node_modules, includes the Prisma CLI
FROM builder AS migrator
CMD ["npx", "prisma", "migrate", "deploy"]
# 4. Production image
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
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
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
CMD ["node", "server.js"]HOSTNAME=0.0.0.0 is the line people miss. Docker sets HOSTNAME to the container ID, and server.js binds to it, so without this line Caddy can't reach the app. The standalone folder also leaves out public/ and .next/static/, which is why they are copied separately. Add a .dockerignore with node_modules, .next, .git and .env* so local builds and secrets stay out of the image.
Build-time vs run-time variables
Anything starting with NEXT_PUBLIC_ is copied into the browser JavaScript during next build. Setting it later in compose.yaml does nothing: it has to be passed as a build argument, and changing it means building a new image. Everything else, including DATABASE_URL, is read by server code at run time and belongs in an env file on the server. Never put a secret in a NEXT_PUBLIC_ variable.
next build prerenders every page it thinks is static. If one of those pages queries the database, the build tries to connect, and there is no database inside the build stage. Make pages that read live data dynamic, for example with export const dynamic = "force-dynamic", so they query at request time instead.
Build both images and tag them with a version (a release number or the Git commit SHA), then push them to a registry such as GitHub Container Registry:
docker build --target runner -t ghcr.io/you/shop:1.4.2 \
--build-arg NEXT_PUBLIC_SITE_URL=https://example.com .
docker build --target migrator -t ghcr.io/you/shop-migrate:1.4.2 .
docker push ghcr.io/you/shop:1.4.2
docker push ghcr.io/you/shop-migrate:1.4.2Building in CI (for example GitHub Actions) and pulling on the server is usually better than building on the server itself. A Next.js build is memory-hungry and can slow down or kill the live app on a small machine.
Step 2: compose.yaml with PostgreSQL and Caddy
On the server, make a folder such as /srv/shop with compose.yaml, Caddyfile, two env files for secrets, and a .env file that holds only the image tag (Compose reads .env automatically for $-substitution in the YAML).
name: shop
x-logging: &default-logging
driver: json-file
options:
max-size: "10m"
max-file: "3"
services:
caddy:
image: caddy:2.10-alpine
restart: unless-stopped
ports:
- "80:80"
- "443:443"
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- caddy_data:/data
- caddy_config:/config
networks: [edge]
depends_on:
web:
condition: service_healthy
logging: *default-logging
web:
image: ghcr.io/you/shop:${APP_TAG:?set APP_TAG in .env}
restart: unless-stopped
env_file: ./web.env
networks: [edge, backend]
depends_on:
db:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "wget -q --spider http://127.0.0.1:3000/api/health || exit 1"]
interval: 30s
timeout: 5s
retries: 3
start_period: 30s
deploy:
resources:
limits:
memory: 768M
logging: *default-logging
db:
image: postgres:16-alpine
restart: unless-stopped
env_file: ./db.env
volumes:
- pgdata:/var/lib/postgresql/data
networks: [backend]
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
interval: 10s
timeout: 5s
retries: 5
deploy:
resources:
limits:
memory: 1G
logging: *default-logging
migrate:
image: ghcr.io/you/shop-migrate:${APP_TAG:?set APP_TAG in .env}
profiles: [tools]
env_file: ./web.env
networks: [backend]
depends_on:
db:
condition: service_healthy
networks:
edge:
backend:
internal: true
volumes:
pgdata:
caddy_data:
caddy_config:example.com {
reverse_proxy web:3000
}APP_TAG=1.4.2POSTGRES_USER=shop
POSTGRES_PASSWORD=paste-output-of-openssl-rand-hex-32
POSTGRES_DB=shopDATABASE_URL=postgresql://shop:paste-output-of-openssl-rand-hex-32@db:5432/shop
AUTH_SECRET=another-long-random-stringWhat each part is doing:
- Only Caddy publishes ports. The app and database have no
ports:section, anddbsits on aninternalnetwork with no route out. This matters because Docker's published ports bypassufw: a stray"5432:5432"would put PostgreSQL on the internet whatever your firewall says. - The database host is
db. Containers on a shared network reach each other by service name, soDATABASE_URLpoints atdb:5432, notlocalhost. - Start order is health-based.
condition: service_healthymakes the app wait untilpg_isreadysucceeds, and Caddy wait until the app answers. The$$stops Compose from substituting the variables itself. - The Postgres version is pinned to a major.
postgres:latestcould jump a major version on a routine pull, and a major upgrade needs a data migration, not just a new image. If you choose PostgreSQL 18 or newer, check the image docs: the recommended volume mount path changed. - Logs and memory are capped so one leaking container can't fill the disk or starve the database.
Generate passwords with openssl rand -hex 32. Hex output avoids characters such as @, / and #, which would otherwise need URL-encoding inside DATABASE_URL. Run chmod 600 *.env .env and keep these files out of Git. Note that POSTGRES_PASSWORD is only applied the first time the volume is initialised; changing it later does not change the database password.
The healthcheck calls a tiny route handler. Add it to the app:
export const dynamic = "force-dynamic";
export function GET() {
return Response.json({ ok: true });
}Connecting to the database without exhausting it
next start and server.js are long-running processes, so create one connection pool when the module loads and reuse it. Opening a new client or pool inside each request or Server Action quickly runs PostgreSQL out of connections (the default limit is 100). With pg, which Drizzle also uses:
import { Pool } from "pg";
const globalForDb = globalThis as unknown as { pool?: Pool };
export const pool =
globalForDb.pool ??
new Pool({
connectionString: process.env.DATABASE_URL,
max: 10,
});
// Reuse the pool across hot reloads in development
if (process.env.NODE_ENV !== "production") globalForDb.pool = pool;Prisma follows the same pattern with a single shared PrismaClient. Whatever you use, set the pool size explicitly and keep (pool size × number of app containers) comfortably under the database's connection limit.
Step 3: Run database migrations on deploy
The production image can't run migrations. Standalone output only contains the files the server needs at run time, and the Prisma CLI is not one of them (it is usually a devDependency anyway). That is what the migrator image is for: it is built from the build stage, so it has the full node_modules, your prisma/ folder and the CLI.
In compose.yaml, the migrate service is in the tools profile, so docker compose up never starts it. You run it on purpose, as a one-off job that exits when it is done. The first deploy looks like this:
cd /srv/shop
docker login ghcr.io
docker compose --profile tools pull
docker compose run --rm migrate
docker compose up -d --waitrun starts db first because of depends_on, applies any pending migrations with prisma migrate deploy, and removes the container afterwards. Using Drizzle? Change the migrator's command to npx drizzle-kit migrate. Never run prisma migrate dev or prisma db push against production: they are for development and can reset or drop data.
Migrations run while the old version of the app is still serving traffic. Write them so the old code keeps working: add a column first and remove the old one in a later release, rather than renaming in one step.
Step 4: Back up PostgreSQL every night
A volume is not a backup; it lives on the same disk as everything else. Take logical dumps with pg_dump, copy them off the server, and delete old local copies. Save this as /srv/shop/backup.sh and make it executable with chmod 700:
#!/bin/sh
set -eu
cd /srv/shop
mkdir -p backups
FILE="backups/db-$(date +%F).dump"
docker compose exec -T db sh -c 'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc' > "$FILE"
# Copy off the server (an rclone remote you have configured; rsync or scp also work)
rclone copy "$FILE" offsite:shop-backups/
# Keep two weeks locally
find backups -name 'db-*.dump' -mtime +14 -deleteSchedule it with sudo crontab -e:
30 2 * * * /srv/shop/backup.sh >> /var/log/shop-backup.log 2>&1Then prove the backup works by restoring it into a scratch database, so live data is never touched:
docker compose exec -T db createdb -U shop restore_test
docker compose exec -T db pg_restore -U shop -d restore_test --no-owner < backups/db-2026-11-08.dump
docker compose exec -T db psql -U shop -d restore_test -c '\dt'
docker compose exec -T db dropdb -U shop restore_testIf the tables and row counts look right, you have a backup. Repeat the test every so often, and after upgrading PostgreSQL.
Cloudflare, HTTPS and image optimisation
Caddy gets a Let's Encrypt certificate the first time a request for example.com arrives, as long as the DNS record points at the server and ports 80 and 443 are open. The simplest order is to bring the stack up with the DNS record set to DNS only (grey cloud), confirm HTTPS works, then switch the record to proxied and set Cloudflare's SSL/TLS mode to Full (strict). If certificate renewals give you trouble behind the proxy, use a Cloudflare Origin certificate in Caddy instead, loaded with the tls directive. The full walkthrough, including locking the server to Cloudflare's IP ranges, is in putting Cloudflare in front of your server.
Cloudflare caches your /_next/static files at the edge, which helps visitors in Sri Lanka even when the server is elsewhere. Server-rendered pages and database queries still go to your origin on every request, so for an app like this, where the server sits relative to your users matters more than it does for a static site. Don't add cache rules for HTML pages that show logged-in data.
The built-in next/image optimiser runs on your server and uses CPU to resize images. On Next.js 15 and newer, standalone output uses sharp automatically. On Next.js 14, add sharp to your dependencies, or standalone builds fall back to a slower optimiser and log a warning. Resized images are cached inside the container, so the cache starts empty after each redeploy; that is normal.
Updating and rolling back
Because the tag lives in .env, an update is: build and push the new images from CI, then on the server back up, change the tag, migrate, and replace the app container.
cd /srv/shop
./backup.sh
sed -i 's/^APP_TAG=.*/APP_TAG=1.4.3/' .env
docker compose --profile tools pull
docker compose run --rm migrate
docker compose up -d --wait web
docker compose logs --tail 100 web--wait returns once the new container reports healthy, or fails if it doesn't. Expect a few seconds of errors while the container is swapped; avoiding that entirely needs two app containers behind Caddy, updated one at a time.
To roll back, set APP_TAG back to 1.4.2 and run docker compose up -d --wait web. The old image is still on the server, so this takes seconds, as long as you haven't pruned images. Rolling back the image does not undo migrations; if a release changed the database in a way the old code can't handle, restore the dump you took before updating. Restart policies, resource limits and pruning are covered in more depth in our Docker production checklist.
Where NevaraCloud fits
If your Next.js app is a static export with no backend or database, it fits our Starter plan at LKR 1,500 a month. A Next.js server with PostgreSQL, like the stack on this page, is our Full-stack plan, from LKR 3,500 a month, which includes daily backups kept for 7 days and priority WhatsApp support. Stacks with workers, Redis or several services run on the Multi-container plan. Final prices are quoted in LKR based on what the app needs; see Docker Compose app hosting or Node.js and Next.js hosting for details.
We don't give root access or sell self-managed VPS servers. If you want to run this stack on your own server and would like help setting it up or fixing it, our deployment help is quoted after we look at your setup.