Last active
April 20, 2024 21:28
-
-
Save danielarrais/b5ac9e83824b14bde272309f398803d7 to your computer and use it in GitHub Desktop.
Import postgresql dumps on docker composer and create multiples 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
services: | |
postgres: | |
image: postgres:latest | |
environment: | |
- 'POSTGRES_DATABASES=database_1,database_2' | |
- 'POSTGRES_PASSWORD=password' | |
- 'POSTGRES_USER=postgres' | |
healthcheck: | |
test: exit $$DUMPS_IMPORTED # Use variable created on multiple-database.sh for checke if dumps were imported | |
interval: 5s | |
timeout: 60s | |
retries: 10 | |
volumes: | |
- ./pg-init:/docker-entrypoint-initdb.d # put multiple-database.sh script on ./pg-init | |
- ./dumps_folder:/dumps # put the dumps files on ./dumps_folder | |
- postgres_data:/var/lib/postgresql/data | |
ports: | |
- '5432:5432' | |
volumes: | |
postgres_data: |
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 | |
export DUMPS_IMPORTED=1 # for health checker | |
function restore_database() { | |
dump_folder="/dumps" | |
dump_file="$dump_folder/$1.sql" | |
if [ -f "$dump_file" ]; then | |
echo "Restoring $dump_file" | |
pg_restore -U "$POSTGRES_USER" -d "$1" -1 "$dump_file" --clean --if-exists --no-owner | |
else | |
echo "Dump for database $1 not found!" | |
fi | |
} | |
function create_database() { | |
local database="$1" | |
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 $POSTGRES_USER; | |
EOSQL | |
} | |
if [ -n "$POSTGRES_DATABASES" ]; then | |
IFS=',' read -ra items <<< "$POSTGRES_DATABASES" | |
echo "Multiple database creation requested: $POSTGRES_DATABASES" | |
for db in "${items[@]}"; do | |
create_database "$db" | |
restore_database "$db" | |
done | |
echo "Multiple databases created" | |
fi | |
export DUMPS_IMPORTED=0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment