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:
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.
1Enable Standalone Output in next.config.ts
next.config.tsStandalone 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.tstypescriptimport type { NextConfig } from 'next'; const nextConfig: NextConfig = { output: 'standalone', }; export default nextConfig;2Configure Prisma DATABASE_URL Using the "postgres" Service Hostname
.envInside 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.
.envdotenvHOSTNAME=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"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)dockerfileFROM 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"]4Deploy Prisma Migrations Safely After Postgres Reports Healthy
terminalStart the stack, confirm postgres is (healthy), and apply Prisma migrations cleanly using prisma migrate deploy (never prisma migrate dev in production).
terminalbashdocker 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.
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.
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.
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.
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:
Fix Prisma P1013 invalid database string errors locally in your browser. Detect unencoded #, @, and ? characters in DATABASE_URL and DIRECT_URL passwords.
Generate a production Nginx reverse proxy for Next.js App Router on port 3000 with Certbot SSL, _next/static caching, streaming responses, and WebSockets.
Configure CORS for Next.js App Router Route Handlers serving external SPAs or widgets. Fix 405 OPTIONS preflights, next.config.ts headers, and Vary: Origin.
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.
Related Docker Compose Stack Guides
Browse all 10 Compose stacks →Docker Compose Node.js + BullMQ Worker + Redis 7 + PostgreSQL 16 Guide
Generate a Docker Compose config for Node.js APIs, BullMQ background workers, Redis 7, and PostgreSQL 16 with native healthchecks and noeviction Redis safety.
Docker Compose FastAPI + PostgreSQL 16 + Celery Worker Healthcheck Guide
Build a production Docker Compose stack for Python FastAPI, PostgreSQL 16, Redis 7, and Celery workers with pg_isready healthchecks and Alembic migrations.
Docker Compose Node.js Express + MongoDB 7 Stack & Healthcheck Guide
Generate a Docker Compose stack for Node.js Express APIs and MongoDB 7 using mongosh ping healthchecks, authSource=admin URIs, and persistent named volumes.
Docker Compose ASP.NET Core 8/9 + PostgreSQL 16 + Redis Cache Guide
Generate a Docker Compose config for ASP.NET Core 8/9 Web API, PostgreSQL 16 (Npgsql), and Redis distributed cache with pg_isready and redis-cli healthchecks.