Skip to content

Instantly share code, notes, and snippets.

@welel
Created March 21, 2024 19:32
Show Gist options
  • Save welel/2fd0435ed671f41db049fa612f4ae196 to your computer and use it in GitHub Desktop.
Save welel/2fd0435ed671f41db049fa612f4ae196 to your computer and use it in GitHub Desktop.
Multiple Docker PostgreSQL databases
POSTGRES_USER=db_name_1
POSTGRES_DB=db_name_1
POSTGRES_PASSWORD=pass123
POSTGRES_MULTIPLE_DATABASES=db_name_1,db_name_2
POSTGRES_PASSWORDS=pass123,pass12345
  1. Create dir contrib/db/docker-entrypoint-initdb.d
  2. Place create-multiple-postgresql-databases.sh in docker-entrypoint-initdb.d.
#!/bin/bash
set -e
set -u
function create_user_and_database() {
local database=$1
local password=$2
echo " Creating user and database '$database'"
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL
CREATE USER $database WITH PASSWORD '$password';
CREATE DATABASE $database;
GRANT ALL PRIVILEGES ON DATABASE $database TO $database;
EOSQL
}
if [ -n "$POSTGRES_MULTIPLE_DATABASES" ] && [ -n "$POSTGRES_PASSWORDS" ]; then
echo "Multiple database creation requested: $POSTGRES_MULTIPLE_DATABASES"
IFS=',' read -ra DBS <<< "$POSTGRES_MULTIPLE_DATABASES"
IFS=',' read -ra PASSWORDS <<< "$POSTGRES_PASSWORDS"
for i in "${!DBS[@]}"; do
db=${DBS[$i]}
password=${PASSWORDS[$i]}
create_user_and_database $db $password
done
echo "Multiple databases created"
fi
version: "3.8"
services:
db:
image: postgres:14
restart: unless-stopped
env_file:
.env
ports:
- "5432:5432"
volumes:
- ./contrib/db/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d:ro
- db:/var/lib/postgresql/data
volumes:
db:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment