composebuilder

Docker Compose: Next.js + PostgreSQL + Redis

Containerize a Next.js app with PostgreSQL 16 and Redis 7 in Docker Compose, using a minimal Dockerfile, healthchecks, named volumes and a production checklist.

When to use this stack

This stack runs a Next.js application with a PostgreSQL 16 database for persistent data and a Redis 7 instance for caching, sessions or rate-limit counters. It is a practical way to ship a full-stack Next.js project, because the app, the database and the cache start together, see each other by service name and can be moved to another server with the same files. The compose file keeps credentials in one .env file, so the same project works on a laptop and on a VPS without code changes.

Choose it when your app needs a relational database and a shared cache, and you want the whole system described in one repository. The Next.js server runs with next start after a production build, so it is suitable for server-rendered pages, API routes and server actions. Do not choose this layout if you only need a static export, which can be served by any web server, or if you need several app replicas behind a load balancer with sticky sessions, which needs its own orchestration. Redis here is a single node without replication, so treat it as a cache and do not store the only copy of important data in it.

The Dockerfile below is intentionally small. It installs dependencies, builds the project and starts the production server on port 3000. Your application code must contain a package.json with a build script and a start script, which are the defaults created by create-next-app.

docker-compose.yml

services:
  app:
    build: ./app
    restart: unless-stopped
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_healthy
    ports:
      - "3000:3000"
    environment:
      NODE_ENV: production
      PORT: 3000
      NEXT_TELEMETRY_DISABLED: 1
      DATABASE_URL: postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
      REDIS_URL: redis://:${REDIS_PASSWORD}@redis:6379/0

  db:
    image: postgres:16-alpine
    restart: unless-stopped
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
      interval: 10s
      timeout: 5s
      retries: 5

  redis:
    image: redis:7-alpine
    restart: unless-stopped
    environment:
      REDIS_PASSWORD: ${REDIS_PASSWORD}
    command: ["redis-server", "--requirepass", "${REDIS_PASSWORD}", "--appendonly", "yes"]
    volumes:
      - redis_data:/data
    healthcheck:
      test: ["CMD-SHELL", "redis-cli -a \"$$REDIS_PASSWORD\" --no-auth-warning ping | grep PONG"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  postgres_data:
  redis_data:

Dockerfile (app/Dockerfile)

Place this file in the ./app folder next to package.json. The whole ./app folder is the build context.

Dockerfile
FROM node:22-alpine
WORKDIR /app

COPY package.json package-lock.json ./
RUN npm ci

COPY . .
RUN npm run build

ENV NODE_ENV=production
EXPOSE 3000
CMD ["npm", "run", "start", "--", "-p", "3000"]

.env

.env
# PostgreSQL superuser for this app, created on the first start
POSTGRES_USER=app
POSTGRES_PASSWORD=CHANGE_ME_postgres_password
POSTGRES_DB=app
# Redis password, passed to redis-server and to the app
REDIS_PASSWORD=CHANGE_ME_redis_password

Start and verify

Shell
docker compose config --quiet

# Build the image from ./app and start the stack
docker compose up -d --build

# db and redis must show "healthy"; app must show "running"
docker compose ps

# Check the app logs for "Ready" and any connection errors
docker compose logs --tail=50 app

# Confirm that the home page answers
curl -I http://localhost:3000

# Confirm that the database accepts connections
docker compose exec db pg_isready -U app -d app

Production checklist

  • Put Next.js behind a reverse proxy with HTTPS, such as Caddy or Nginx, and do not expose the app over plain HTTP on the public internet.
  • Use passwords made only of letters and numbers for POSTGRES_PASSWORD and REDIS_PASSWORD, or URL-encode them, because they appear inside DATABASE_URL and REDIS_URL.
  • Never commit .env. Keep secrets such as session keys in the environment, not in source files, and do not use NEXT_PUBLIC_ for them.
  • Keep Redis on the internal Docker network. This file does not publish port 6379 or 5432, and that is the correct default.
  • Pin the Node, PostgreSQL and Redis tags and upgrade them after you test a restore.
  • Back up the postgres_data volume with pg_dump on a schedule, and test restoring the dump to a new container.
  • Add a .dockerignore file with node_modules, .next and .env so secrets and local builds never enter the image.
  • Set a memory limit on the app service if your host is small, so a runaway build cannot starve the database.

Common problems

  • Symptom: The build fails with “Module not found” only inside Docker. Cause: A dependency is listed only in a global install on your machine, or a file is excluded by .dockerignore. Fix: Add the package to package.json, regenerate package-lock.json and rebuild with docker compose build –no-cache app.
  • Symptom: The app exits with “ECONNREFUSED” for PostgreSQL. Cause: The host name must be db, not localhost, inside the containers. Fix: Keep @db:5432 in DATABASE_URL and restart with docker compose up -d.
  • Symptom: Redis returns NOAUTH errors. Cause: The client connects without the password or with the wrong one. Fix: Use the redis://:password@redis:6379/0 form with the same value as REDIS_PASSWORD.
  • Symptom: The page shows a blank 500 error only in production. Cause: An environment variable is needed at build time but is missing from the build. Fix: Check the app logs with docker compose logs app, then pass the value as a build argument or read it at runtime.
  • Symptom: The container restarts in a loop. Cause: The start command exits early, often because the build folder is missing. Fix: Confirm the build step succeeded, check that .next exists in the image, and read the logs.

Variations

  • Development with hot reload: Create a separate compose.dev.yml that uses the node:22-alpine image, bind-mounts ./app to /app and runs npm run dev. Run it with docker compose -f compose.dev.yml up. Keep the production file unchanged.
  • Next.js standalone output: Set output to standalone in next.config, copy only the .next/standalone folder into a smaller runtime image, and start it with node server.js. This reduces image size.
  • Use Valkey instead of Redis: Replace the redis image with valkey/valkey:8-alpine, which uses the same protocol, and keep the same REDIS_URL variable name. Test the client library before switching.

Questions

Which folder does the compose file use for my Next.js code?

The app service builds from ./app, so your Next.js project (with package.json) must live in that folder. The code is copied into the image at build time and is not bind-mounted.

Why does the app start before the database is ready?

It should not, because depends_on uses condition: service_healthy for both db and redis. If it still fails, check that the healthchecks pass with docker compose ps.

Can I use this for hot reload during development?

Not with this file. For development, run npm run dev on the host or add a separate override file that bind-mounts ./app and runs next dev.

Adapt this stack

Load these files into the builder to rename services, change ports, add a cache or a proxy, and generate fresh passwords for the .env.

Open in builder
  • Laravel + PostgreSQL + Redis

    Run a Laravel app on Apache with PostgreSQL 16 and Redis 7 in Docker Compose, with a Dockerfile, queue and cache settings, volumes and a production checklist.

    • app
    • db
    • redis
    Difficulty: Intermediate
  • Django + PostgreSQL + Celery

    Run a Django app with Gunicorn, PostgreSQL 16, Redis 7 as the Celery broker and a Celery worker in Docker Compose, with healthchecks and a production checklist.

    • web
    • worker
    • db
    • redis
    Difficulty: Advanced
  • Nuxt + PostgreSQL

    Run a Nuxt 3 app built with Nitro and PostgreSQL 16 in Docker Compose, with a Node 22 Dockerfile, a database healthcheck, persistent data and a checklist.

    • app
    • db
    Difficulty: Intermediate
  • Rails + PostgreSQL + Redis

    Run a Ruby on Rails app with PostgreSQL 16 and Redis 7 in Docker Compose, with a slim Ruby 3.3 Dockerfile, database setup, persistent data and a checklist.

    • web
    • db
    • redis
    Difficulty: Intermediate

Browse more Web & Frameworks stacks or the full library.