Skip to content

Instantly share code, notes, and snippets.

@gsong
Last active September 30, 2021 14:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsong/d02e1bca0a9fc2dc0d6bf79ff123de98 to your computer and use it in GitHub Desktop.
Save gsong/d02e1bca0a9fc2dc0d6bf79ff123de98 to your computer and use it in GitHub Desktop.
Docker compose file to start PG and PGAdmin
version: "3.8"
services:
pg:
image: postgres:alpine
container_name: dev-postgres
hostname: pg
environment:
POSTGRES_USER: me
POSTGRES_PASSWORD: password
POSTGRES_DB: my-db
volumes:
- ./.data/db:/var/lib/postgresql/data
networks:
- db
healthcheck:
test: pg_isready -U postgres || exit 1
stop_grace_period: 1m
pgadmin:
image: dpage/pgadmin4
container_name: dev-pgadmin
hostname: pgadmin
environment:
PGADMIN_DEFAULT_EMAIL: me@example.com
PGADMIN_DEFAULT_PASSWORD: password
volumes:
- ./.data/pgadmin:/var/lib/pgadmin
ports:
- 8008:80
depends_on:
- postgres
networks:
- db
networks:
db:
@gsong
Copy link
Author

gsong commented Aug 25, 2021

How to Use This

  1. Copy this gist to a file named docker-compose.yml in any directory.

  2. Start the service containers:

    docker-compose up -d
  3. Wait for a few minutes as both services take some time to start up.

  4. Navigate to http://localhost:8008.

  5. Log into PGAdmin using ${PGADMIN_DEFAULT_EMAIL} and ${PGADMIN_DEFAULT_PASSWORD} (as set in docker-compose.yml).

  6. Click on Add New Server under Quick Links section.

  7. Name the server anything you want, e.g. dev-db.

  8. Click on the Connection tab, and fill in the following:

    Field Value
    Host name/address pg
    Username ${POSTGRES_USER} or postgres if not set
    Password ${POSTGRES_PASSWORD}
  9. Save

When you're done with everything, destroy the containers:

docker-compose down

How to Access PSQL

After you've started the containers:

docker-compose exec -u postgres pg psql ${POSTGRES_DB} ${POSTGRES_USER}

Using the example above, the command would be:

docker-compose exec -u postgres pg psql my-db me

Notes About docker-compose.yml

pg

  • You can specify any Postgres username you want, if you leave out POSTGRES_USER, it defaults to postgres.
  • You can specify any password you want for the Postgres user.
  • You can create a starting database using POSTGRES_DB, in this case my-db, if you leave out this variable, no database will be created by default.
  • Notice I'm not exposing Postgres to a host port, since it's not needed in this use case.

pgadmin

  • Map host directory to /var/lib/pgadmin so PGAdmin settings are retained.
  • We map to http://localhost:8008 so we don't try to use a privileged port.

networks

We define a network named db and attach both services to it. This is what allows us to refer to the pg service by name rather than by IP address.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment