1001Ferramentas
🐘Dev

docker-compose PostgreSQL Generator

Generate a ready-to-use docker-compose for PostgreSQL, with user, password, database and a persistent volume set up. Spin up your local DB with one command.

YAML

β€”

Local Postgres in one compose up

You need a database for development and you would rather not install Postgres on the machine, with a service starting at boot and a cluster to clean up later. Pick the image tag (16-alpine, 17, whatever the project uses) and a password, and the YAML comes out ready: one service, port 5432 published and a named volume pgdata mounted at /var/lib/postgresql/data, where Postgres keeps its files.

The generated file sets only POSTGRES_PASSWORD, and that is not an oversight: in the official image POSTGRES_USER defaults to postgres when omitted, and POSTGRES_DB defaults to the user name. So you end up with user postgres and database postgres, which is fine for development. Add both variables yourself if you want different names. There is also no version key on top, since it is obsolete in the current Compose spec.

The catch: those variables only apply on the very first run, while the data directory is empty and initdb executes. Changing the password in the YAML afterwards does nothing. To make it stick you need docker compose down -v, which deletes the volume and the data with it. The 5432:5432 mapping also publishes on every interface, so on an exposed host use 127.0.0.1:5432:5432, since the rule Docker adds bypasses ufw.

Frequently asked questions

I already have Postgres installed, will the port clash?
Yes, both want 5432. Publish on a different host port, such as 5433:5432, and connect through 5433.
How does another container reach this database?
By service name: host postgres, port 5432. Compose creates a default network and resolves the name, so in that setup you do not even need to publish the port on the host.
Do I lose the data when I bring the containers down?
Not with docker compose down: the pgdata volume stays and the next up reuses it. With docker compose down -v the volume is removed and the database comes back empty.

Related Tools