Skip to content

Instantly share code, notes, and snippets.

@Kostanos
Last active June 20, 2020 11:25
Show Gist options
  • Save Kostanos/74197f2b3e3cfcf985681505f9c76c5a to your computer and use it in GitHub Desktop.
Save Kostanos/74197f2b3e3cfcf985681505f9c76c5a to your computer and use it in GitHub Desktop.
Creates multiple databases with postgresql docker image
# PostgreSQL with multiple databases created
* Just copy all these files to the folder
* Change the name of your databases, and add/remove as many DB that you need in docker-compos.yml
* docker-compose build; docker-compose up
And vuala :)
#!/bin/bash
# Will create up to 50 databases
# DB_NAME_x and DB_USER_x varibles should be defined
set -e
POSTGRES="psql --username ${POSTGRES_USER} ${POSTGRES_DB}"
export END=50
export i=1; while [[ $i -le $END ]]; do
var_db_name="DB_NAME_$i"
var_db_user="DB_USER_$i"
if [[ -z "${!var_db_name}" ]] || [[ -z "${!var_db_user}" ]] ; then
break
fi
echo "----------------------------------"
echo "Creating database: ${!var_db_name}"
echo "----------------------------------"
$POSTGRES <<EOSQL
CREATE DATABASE "${!var_db_name}" OWNER "${!var_db_user}";
EOSQL
((i = i + 1))
done
#!/bin/bash
set -e
POSTGRES="psql --username ${POSTGRES_USER} ${POSTGRES_DB}"
echo "----------------------------------"
echo "Creating initial schema for all DBs"
echo "----------------------------------"
$POSTGRES -f /dbInit.sql
#!/bin/sh
set -e
echo "The same user(${POSTGRES_USER}) and password is used for all DBs...."
SELECT 'DB Schemas here...'
version: '3.1'
# Main DB services
# PostgresQL
services:
sb-pg:
build:
context: ./
dockerfile: Dockerfile
container_name: my-pg
networks:
- my_db
environment:
POSTGRES_USER: my_user
POSTGRES_DB: my_db
POSTGRES_PASSWORD: my_pass
DB_NAME_1: my_db_1
DB_USER_1: my_user
DB_NAME_2: my_db_2
DB_USER_2: my_user
ports:
- 5432:5432
volumes:
- ../db-data/postgres:/var/lib/postgresql/data
FROM postgres:12-alpine
LABEL owner="Kostya Kostyushko"
# Custom initialization scripts
COPY ./create_user.sh /docker-entrypoint-initdb.d/10-create_user.sh
COPY ./create_db.sh /docker-entrypoint-initdb.d/20-create_db.sh
COPY ./dbInit.sql /dbInit.sql
COPY ./create_db_schemas.sh /docker-entrypoint-initdb.d/20-create_db_schemas.sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment