PostGIS with Docker Compose

In How to use PostGIS in a docker container I explained how to start two docker containers, with PostGIS and with PgAdmin4, with docker run and how to use them.

There is another way: we can set up a configuration file compose.yaml and build and start both containers with docker compose.

This way

  • It is easy to recreate containers with the same settings
  • Networking between the containers will be easier

The following compose.yaml creates almost the same containers as in my old blog post (see there for information about most of the options):

name: dockerpostgis

services:
  db:
    image: postgis/postgis
    restart: always
    ports: 
      - "5432:5432"
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: mypassword
      POSTGRES_DB: postgres # default database
    volumes:
      - pg_data:/var/lib/postgresql/data
  pgadmin4:
    image: dpage/pgadmin4
    restart: always
    ports:
      - "80:80"
    environment:
      PGADMIN_DEFAULT_EMAIL: user@domain.com
      PGADMIN_DEFAULT_PASSWORD: supersecred
    volumes:
      - pgadmin_data:/var/lib/pgadmin

volumes:
  pg_data:
  pgadmin_data:

This will start two services, running one container each. A “service” is defined in the config file by the image and some runtime arguments. The service db will be a container running PostGIS, the container name will most likely be “db-1”. Note that docker compose will add “dockerpostgis-db-1” and “db” to the list of DNS names, so we can use “db” as the hostname in pgAdmin.

Also note that the volumes are managed within the “dockerpostgis” scope defined by the yaml file. They will be listed as dockerpostgis_pg_data and dockerpostgis_pgadmin_data and any volumes created with docker run will be ignored. To reuse existing volumes, you can try to change the last lines of compose.yaml to:

volumes:
  pg_data:
    external: true
  pgadmin_data:
    external: true

To start (and build) the containers, run in the folder with your compose.yaml:

docker compose up

Or send the process into the background (detached):

docker compose up -d

In the first case, you can stop the containers with “Strg + C”, in the second case, stop it with:

docker compose stop

To stop and remove the containers, run:

docker compose down