Docker Compose Builder · Next.js / Prisma + Postgres

Docker Compose Next.js Standalone + Prisma + PostgreSQL 16 Stack Guide

Generate a Compose Specification docker-compose.yml and matching .env.example for Next.js / Prisma + Postgres with native binary healthchecks, service_healthy boot ordering, and firewall-safe port bindings.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Runtime & Data Services

2. Healthchecks, Workers & Security

# docker-compose.yml — Modern Compose Specification (no obsolete 'version:' attribute)
# Generated by OpsCheck DevTools (Next.js Standalone)
name: nextjs_prisma_stack

services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
    restart: unless-stopped
    env_file:
      - .env
    ports:
      - "127.0.0.1:3000:3000"
    environment:
      DB_HOST: postgres
      DB_PORT: "5432"
    depends_on:
      postgres:
        condition: service_healthy
    networks:
      - app_network

  postgres:
    image: postgres:16-alpine
    restart: unless-stopped
    environment:
      POSTGRES_DB: ${DB_DATABASE:-app_db}
      POSTGRES_USER: ${DB_USERNAME:-app}
      POSTGRES_PASSWORD: ${DB_PASSWORD:-change_me_strong}
    # Kept strictly internal on app_network (prevents Docker iptables UFW bypass)
    expose:
      - "5432"
    volumes:
      - db_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER:-app} -d $${POSTGRES_DB:-app}"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 20s
    networks:
      - app_network

networks:
  app_network:
    driver: bridge

volumes:
  db_data:
Service Boot Orderbridge: app_network
postgres(healthy)web

Healthcheck & Security Diagnostics

Compose Spec v2+
  • passStartup Race Condition Prevented (condition: service_healthy)

    web will wait until postgres pass their native healthchecks before starting.

  • infoInternal Bridge DNS Hostnames (Never Use localhost Inside Containers)

    Connect over the shared app_network using Docker service names: DB_HOST=postgres (port 5432). Inside the "web" container, 127.0.0.1/localhost points only to "web" itself and always refuses DB/broker connections.

  • passFirewall-Safe Port Exposure Enabled (127.0.0.1 / Internal expose:)

    Database and broker ports stay strictly isolated on app_network via expose:, and app ports bind to 127.0.0.1 so Docker never bypasses host UFW/nftables rules.

  • passNative Probe Binaries Used (pg_isready)

    Generated healthchecks invoke built-in service binaries rather than curl or wget, avoiding false "unhealthy" states in minimal Alpine and slim official images.

  • passPersistent Named Volumes Declared (db_data)

    Top-level named volumes preserve database tables and broker queues across container rebuilds and "docker compose down" (data is only removed if you pass -v).

Runs locally in your browser. Compose YAML and environment templates are generated client-side.

Typical Container Boot & Connection Error (Next.js / Prisma + Postgres)

When depends_on lacks condition: service_healthy or internal service hostnames are misconfigured in .env, container logs typically surface this error during startup:

docker compose logs (Startup Failure)

Error: P1001: Can't reach database server at `postgres:5432` — Please make sure your database server is running at `postgres:5432`.

Container Boot Ordering, Bridge DNS & Persistence for Next.js / Prisma + Postgres

Self-hosting a full-stack Next.js App Router application paired with Prisma ORM and PostgreSQL 16 in Docker Compose offers tiny image footprints (via output: "standalone") and zero cold-start latency; provided you navigate Next.js build-time vs. runtime environment variables and Prisma's database readiness checks correctly.

A classic Docker + Prisma failure occurs immediately during container boot: Prisma executes prisma migrate deploy or your first Server Component queries PostgreSQL before Postgres finishes initializing its data directory, throwing Prisma error P1001 ("Can't reach database server at postgres:5432"). Wiring postgres:16-alpine with a native pg_isready healthcheck and condition: service_healthy eliminates this boot race entirely.

Next.js also introduces a subtle Docker build trap: static prerendering during docker build attempts to query PostgreSQL when no postgres container exists yet inside the build sandbox. Marking database-backed App Router pages with export const dynamic = "force-dynamic" (or skipping DB queries during build) ensures docker compose build completes reliably while runtime Server Components connect cleanly to postgres:5432 over app_network.

Using Docker Compose's bindLocalhostOnly mode (127.0.0.1:3000:3000 for Next.js and expose: ["5432"] for PostgreSQL) ensures your host Nginx reverse proxy reaches Next.js cleanly over loopback while PostgreSQL stays completely unreachable from the public internet.

Finally, because Next.js standalone mode runs node server.js on HOSTNAME=0.0.0.0 inside the container, remember to set HOSTNAME=0.0.0.0 in your container environment; otherwise Next.js can bind to the container's internal hostname interface and drop health checks or Nginx proxy connections.

When deploying Next.js standalone containers alongside Prisma and PostgreSQL 16 on a Linux host, pair Compose healthchecks with lightweight Prisma connection pooling parameters (connection_limit in DATABASE_URL) so sudden traffic spikes do not overwhelm Postgres worker processes. Running docker compose ps and testing both cold page renders and authenticated mutations guarantees your database volume, SSL reverse proxy, and Prisma engine binaries work cleanly after container rebuilds.

Step-by-Step Next.js / Prisma + Postgres Docker Compose Setup Guide

Follow each step below to pair the generated Compose file with accurate container DNS variables, safe database migrations, and zero-downtime restarts.

  1. 1Enable Standalone Output in next.config.ts

    next.config.ts

    Standalone output traces only the exact Node.js runtime files and Prisma engine binaries needed, shrinking production Docker images from ~1.2 GB down to ~180 MB.

    next.config.tstypescript
    import type { NextConfig } from 'next';
    
    const nextConfig: NextConfig = {
      output: 'standalone',
    };
    
    export default nextConfig;
  2. 2Configure Prisma DATABASE_URL Using the "postgres" Service Hostname

    .env

    Inside Docker Compose, Prisma connects over app_network to host "postgres" on port 5432. Set HOSTNAME=0.0.0.0 so Next.js listens on all interfaces inside the container.

    .envdotenv
    HOSTNAME=0.0.0.0
    PORT=3000
    DB_DATABASE=app_db
    DB_USERNAME=app
    DB_PASSWORD=change_me_strong
    DATABASE_URL="postgresql://app:change_me_strong@postgres:5432/app_db?schema=public"
  3. 3Include OpenSSL & Prisma Engine Binaries in Alpine/Slim Dockerfiles

    Dockerfile (runner stage snippet)

    If using node:22-alpine for the runner stage, install openssl so Prisma's query engine starts cleanly without libssl shared-library crashes.

    Dockerfile (runner stage snippet)dockerfile
    FROM node:22-alpine AS runner
    WORKDIR /app
    RUN apk add --no-cache openssl
    ENV NODE_ENV=production
    ENV HOSTNAME="0.0.0.0"
    COPY --from=builder /app/.next/standalone ./
    COPY --from=builder /app/.next/static ./.next/static
    COPY --from=builder /app/prisma ./prisma
    EXPOSE 3000
    CMD ["node", "server.js"]
  4. 4Deploy Prisma Migrations Safely After Postgres Reports Healthy

    terminal

    Start the stack, confirm postgres is (healthy), and apply Prisma migrations cleanly using prisma migrate deploy (never prisma migrate dev in production).

    terminalbash
    docker compose up -d --build
    docker compose exec web npx prisma migrate deploy
    docker compose ps

Common Next.js / Prisma + Postgres Docker Compose Pitfalls

Avoid these three container orchestration mistakes before deploying your Compose stack onto staging or production servers.

Pitfall 1

NEXT_PUBLIC_* Variables Missing Inside Built Client Bundles

Next.js inlines NEXT_PUBLIC_* environment variables at docker build time, not at docker compose up runtime. Pass public variables as Docker build args (ARG NEXT_PUBLIC_API_URL) while keeping DATABASE_URL strictly runtime-only in .env.

Pitfall 2

Prisma P1001 Error During docker build Static Page Generation

If a Server Component queries Prisma without export const dynamic = "force-dynamic", next build tries to connect to postgres:5432 while building the image and fails with P1001 because Compose networking does not exist during image builds.

Pitfall 3

Forgetting HOSTNAME=0.0.0.0 in Next.js Standalone Containers

Docker injects the container ID into the HOSTNAME env var, causing node server.js to bind exclusively to that container IP instead of 0.0.0.0. Setting ENV HOSTNAME="0.0.0.0" prevents intermittent 502 errors from host proxies.

Related Tools

Pair Your Docker Compose Stack With .env Linting, Nginx TLS & CORS Checks

Validate your .env file for unescaped $$ interpolation or leaked secrets, configure Nginx DNS resolution, and verify cross-origin headers:

Frequently Asked Questions

Why does Prisma throw P1001 even though PostgreSQL is listed under depends_on?
Without condition: service_healthy and a pg_isready healthcheck, Docker starts the Next.js container immediately before PostgreSQL finishes opening port 5432. Enabling healthchecks in the builder above fixes P1001 startup races.
Should I run prisma migrate deploy in the Dockerfile CMD?
For single-instance VPS deployments, running npx prisma migrate deploy in an entrypoint script before node server.js is convenient. For multi-replica clusters, run migrations as a single pre-deploy step so two containers never race to alter tables simultaneously.
How do I persist PostgreSQL data across Next.js rebuilds?
The generated docker-compose.yml mounts a top-level named volume (db_data:/var/lib/postgresql/data). Rebuilding your Next.js image with docker compose up -d --build web leaves your PostgreSQL data untouched.
Can I add Redis for Next.js cache handlers or rate limiting in the same file?
Yes. Select Redis 7 in the Cache / Broker dropdown above to add a persistent redis:7-alpine container with redis-cli ping healthchecks and matching REDIS_URL environment variables.
Browse all 10 Compose stacks →