Search code examples
postgresqldockerdocker-composepostgis

How do I add PostGIS to my PostgreSQL setup using pure docker-compose


We have been using the following docker-compose.yml to account for PostgreSQL (another other redacted) dependencies.

version: '3.5'

services:
  postgres132:
    image: postgres:13.2
    restart: always
    environment:
      POSTGRES_PASSWORD: 'user'
      POSTGRES_USER: 'pass'
      POSTGRES_DB: 'db'
    volumes:
        - ./data/postgres:/var/lib/postgresql/data
    ports:
        - 5432:5432

Now, I need to add PostGIS support to the same container. Is that possible and how can I do that? I'm new to both Postgres and PostGIS so forgive my ignorance about the same.


Solution

  • Why not use Dockerfile specfic to add postgis?

    Change your "image" property to "build" property to link a Dockerfile.

    Your docker-compose.yml would look like this:

    version: '3'
    services:
      db:
        container_name: db
        build:
          context: .
          dockerfile: Dockerfile-db
        restart: always
        environment:
          POSTGRES_USER: user
          POSTGRES_PASSWORD: pass
          POSTGRES_DB: db_name
        ports:
          - "5432:5432"
    

    Then create a text file named Dockerfile-db in the same path as docker-compose.yml with the following content:

    FROM postgres:14.1
    
    
    RUN apt-get update && apt-get  install -y postgresql-14-postgis-3  
    
    
    CMD ["/usr/local/bin/docker-entrypoint.sh","postgres"]
    

    notice that you can specify the PostGIS version that goes along with your Postgresql version.

    This way you can install all you need in the container by extending the Dockerfile-db

    Notice: your db container now has PostGIS but we need to create the extension in the DB and for that you should run CREATE EXTENSION postgis; you only need to do this once if you use volumes.

    Bonus: One way of doing it's by preparing a directory called db/ with init.sql file and write something like CREATE EXTENSION postgis ; and persist it as a volume in docker compose so the final format for your docker-compose would be :

    version: '3'
    services:
      db:
        container_name: db
        build:
          context: .
          dockerfile: Dockerfile-db
        restart: always
        environment:
          POSTGRES_USER: user
          POSTGRES_PASSWORD: pass
          POSTGRES_DB: db_name
        ports:
          - "5432:5432"
        volumes:
          - ./db:/docker-entrypoint-initdb.d/
          - database_volume:/var/lib/postgresql/data
    
    volumes:
      database_volume:
    
    

    this way the postgresql will run this script and create your extensions