Home / Configs / Containers / docker-compose for PostgreSQL

docker-compose for PostgreSQL: example file and generator

Run a local PostgreSQL database that keeps its data.

For Docker Desktop (Windows, macOS) or Docker Engine with the Compose plugin (Linux). Use "docker compose", not "docker-compose".

This docker-compose file starts a PostgreSQL database on your computer with one command and keeps your data between restarts. Choose your version, user, password and port below, then run docker compose up -d.

Create your config file

Type your own values. The file below updates as you type, and nothing you type leaves your browser.

Click Generate for a strong one
Change if 5432 is taken

docker-compose.yml
services:
  db:
    image: postgres:16
    restart: unless-stopped
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: change-me
      POSTGRES_DB: appdb
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:

How this setup works

Diagram: docker compose up, then Postgres container, then pgdata volume
docker compose up (one command) → Postgres container (your port) → pgdata volume (data is kept)

Step-by-step setup

  1. Install Docker Desktop (Windows, macOS) or Docker Engine (Linux).
  2. Save the config above as docker-compose.yml in an empty folder.
  3. Change the password.
  4. Run docker compose up -d.
  5. Connect: psql -h localhost -p 5432 -U app appdb.

What the important lines mean

Common errors and how to fix them

port is already allocated
Something else already uses port 5432. Pick another port above, such as 5433.
password authentication failed
The password is only set the first time. Reset with docker compose down -v (this deletes the data).

Frequently asked questions

How do I connect to PostgreSQL running in Docker?
Use host localhost, the port you chose (5432 by default), and the user, password and database from the file. For example: psql -h localhost -U app appdb.
Will I lose my data when I stop the container?
No, as long as the volume is in the file. Data is lost only if you run docker compose down -v, which deletes the volume.
Why does my password not change when I edit the file?
Postgres reads the password only the first time it creates the database. To start fresh, run docker compose down -v and then up again. This deletes the data.

Written for: Docker 27, Compose v2, Postgres 16 · Updated 2026-10-02

Free tools that help

Fix a problem with this setup

More container configs

See all 41 config generators