- Create dir
contrib/db/docker-entrypoint-initdb.d
- Place
create-multiple-postgresql-databases.sh
indocker-entrypoint-initdb.d
.
-
-
Save welel/2fd0435ed671f41db049fa612f4ae196 to your computer and use it in GitHub Desktop.
Multiple Docker PostgreSQL databases
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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