Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple PostgreSQL database creation in a docker-compose file

I'm building an app using PostgreSQL ... But I need 2 DB's ... Is there an easy way to add 2 DB's using the same username / password / host? One called API and one called TESTING

My current docker-compose DB setup is as follows;

# PostgreSQL Service
postgresql:
image: postgres
container_name: postgresql
restart: unless-stopped
tty: true
ports:
  - "5432:5432"
environment:
  - POSTGRES_USER=dev
  - POSTGRES_PASSWORD=development1234
  - POSTGRES_DB=api
  - SERVICE_TAGS=dev
  - PGDATA=/tmp
volumes:
  - ./dev/dbdata:/var/lib/postgresql/data
networks:
  - app-network
like image 252
CodeSauce Avatar asked Jan 01 '23 09:01

CodeSauce


2 Answers

You'll have to create a separate init script to create the second database. Assuming you are using POSTGRES_DB=api as listed, you can create a script create_second_db.sh like so:

#!/bin/bash
set -e

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    CREATE DATABASE testing;
EOSQL

Then, put create_second_db.sh in /docker-entrypoint-initdb.d/:

...
volumes:
  - ./dev/dbdata:/var/lib/postgresql/data
  - ./create_second_db.sh:/docker-entrypoint-initdb.d/create_second_db.sh
...

Bear in mind as per the documentation, "scripts in /docker-entrypoint-initdb.d are only run if you start the container with a data directory that is empty"

like image 170
richyen Avatar answered Jan 02 '23 22:01

richyen


postgres:
    container_name: postgres
    image: postgres
    volumes:
      - ./docker-postgresql-multiple-databases:/docker-entrypoint-initdb.d
    ports:
      - "5432:5432"
    restart: unless-stopped
    environment:
      - POSTGRES_MULTIPLE_DATABASES=db1,postgres:db2,postgres:db3,postgres
      - POSTGRES_PASSWORD=changeme
      - POSTGRES_USER=postgres

and in folder docker-postgresql-multiple-databases you should have script like this

#!/bin/bash

set -e
set -u

function create_user_and_database() {
    local database=$(echo $1 | tr ',' ' ' | awk  '{print $1}')
    local owner=$(echo $1 | tr ',' ' ' | awk  '{print $2}')
    echo "  Creating user and database '$database'"
    psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL
        CREATE DATABASE $database;
        GRANT ALL PRIVILEGES ON DATABASE $database TO $owner;
EOSQL
}

if [ -n "$POSTGRES_MULTIPLE_DATABASES" ]; then
    echo "Multiple database creation requested: $POSTGRES_MULTIPLE_DATABASES"
    for db in $(echo $POSTGRES_MULTIPLE_DATABASES | tr ':' ' '); do
        create_user_and_database $db
    done
    echo "Multiple databases created"
fi
like image 39
Spasoje Petronijević Avatar answered Jan 03 '23 00:01

Spasoje Petronijević