Docker Recipes
devopsdockerRecipeBeginner
PostgreSQL with Docker Compose
Step-by-step recipe to set up a production-ready PostgreSQL instance with persistent volumes, custom initialization scripts, health checks, and pgAdmin.
Verified: 2026-09-30
Tested on:postgres 16-alpine, docker-compose v2.x
Platforms:
linuxmacoswindows
#postgresql#docker#docker-compose#database
Goal
Run a containerized PostgreSQL database with persistent volume storage, automatic SQL schema initialization on first boot, and integrated health checks using Docker Compose.
Step-by-Step Implementation
```bash
mkdir -p postgres-compose/init-scripts
cd postgres-compose
``````yaml
services:
postgres:
image: postgres:16-alpine
container_name: dev_postgres
restart: unless-stopped
environment:
POSTGRES_USER: ${POSTGRES_USER:-appuser}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-supersecret}
POSTGRES_DB: ${POSTGRES_DB:-appdb}
ports:
- "127.0.0.1:5432:5432"
volumes:
- pgdata:/var/lib/postgresql/data
- ./init-scripts:/docker-entrypoint-initdb.d:ro
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-appuser} -d ${POSTGRES_DB:-appdb}"]
interval: 5s
timeout: 5s
retries: 5
pgadmin:
image: dpage/pgadmin4:latest
container_name: dev_pgadmin
restart: unless-stopped
environment:
PGADMIN_DEFAULT_EMAIL: admin@example.com
PGADMIN_DEFAULT_PASSWORD: adminpassword
ports:
- "127.0.0.1:5050:80"
depends_on:
postgres:
condition: service_healthy
volumes:
pgdata:
``````sql
-- init-scripts/01-init.sql
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO users (email) VALUES ('alice@example.com'), ('bob@example.com');
```Connecting to PostgreSQL
From Host CLI using psql
psql -h localhost -p 5432 -U appuser -d appdbFrom Inside Docker Container
docker compose exec -it postgres psql -U appuser -d appdbRelated Topics
Dockerize a Next.js App (Production Multi-Stage)
Create an optimized, secure multi-stage Dockerfile for Next.js App Router using standalone output with image size under 120MB.
Node.js + PostgreSQL with Docker Compose
Complete full-stack development environment setup connecting a Node.js Express/TypeScript backend with a containerized PostgreSQL database using Docker Compose.