Creating a containerized PostgreSQL database using Docker is straightforward.
Below are several common approaches.
Quickest Way (Single Command)
Run PostgreSQL in a container with a default configuration.
docker run -d \
--name postgres-db \
-e POSTGRES_PASSWORD=mysecretpassword \
-p 5432:5432 \
postgres
What this does
-d→ runs container in background--name postgres-db→ container name-e POSTGRES_PASSWORD→ sets admin password-p 5432:5432→ exposes PostgreSQL port to hostpostgres→ official PostgreSQL image
You can now connect using:
Host: localhost
Port: 5432
User: postgres
Password: mysecretpassword
Production-Friendly Setup (With Persistent Storage)
Without volumes, data will disappear if the container is deleted. Use a Docker volume.
Step 1: Create a volume
docker volume create postgres-data
Step 2: Run container with volume
docker run -d \
--name postgres-db \
-e POSTGRES_USER=myuser \
-e POSTGRES_PASSWORD=mypassword \
-e POSTGRES_DB=mydatabase \
-v postgres-data:/var/lib/postgresql/data \
-p 5432:5432 \
postgres:16
Environment Variables
| Variable | Purpose |
|---|---|
| POSTGRES_USER | database user |
| POSTGRES_PASSWORD | user password |
| POSTGRES_DB | database created at startup |
Connecting to the Database
From host machine, if you have PostgreSQL client installed:
psql -h localhost -U myuser -d mydatabase
From inside the container
docker exec -it postgres-db psql -U myuser -d mydatabase
Using Docker Compose (Recommended for Projects)
Step 1: Create a docker-compose.yml file:
version: "3.9"
services:
postgres:
image: postgres:16
container_name: postgres-db
restart: always
environment:
POSTGRES_USER: myuser
POSTGRES_PASSWORD: mypassword
POSTGRES_DB: mydatabase
ports:
- "5432:5432"
volumes:
- postgres-data:/var/lib/postgresql/data
volumes:
postgres-data:
Step 2: Start it
docker compose up -d
Stop container:
docker compose down
Check Container Status
List all running containers
docker ps
View logs:
docker logs postgres-db
Backup/Restore the Database
Backup:
docker exec postgres-db pg_dump -U myuser mydatabase > backup.sql
Restore:
docker exec -i postgres-db psql -U myuser mydatabase < backup.sql
Connecting From Applications
Example connection string:
postgresql://myuser:mypassword@localhost:5432/mydatabase
Useful Docker Commands for the Database
Stop container:
docker stop postgres-db
Start container:
docker start postgres-db
Delete container:
docker rm postgres-db