#!/bin/bash if [ "$(id -u)" != "0" ]; then echo -e "\033[31mThis script requires superuser rights\033[0m" exit 0 fi if [ -z "$1" ] || [ -z "$2" ]; then echo "Please provide both the POSTGRES_DB and POSTGRES_USER as arguments" exit 1 fi trap 'echo -e "\033[31mpostgres.sh: Something went wrong\033[0m"; exit 1' ERR set -e export DEBIAN_FRONTEND=noninteractive PGDB="$1" PGUSER="$2" CURRENT_MONTH=$(date +%Y-%m) CURRENT_DATE=$(date +%Y-%m-%d) CURRENT_DATETIME=$(date +%d-%m-%Y_%H%M%S) BACKUPS_PATH=/backups/postgres DOCKER_SERVICE_NAME=postgres BACKUP_FOLDER=$BACKUPS_PATH/$PGDB echo 'check BACKUP_FOLDER...' mkdir -p "$BACKUP_FOLDER" echo 'Creating PostgreSQL backups...' cd "$BACKUP_FOLDER" if [ -f 'dump_'"$PGDB"'.sql' ]; then rm 'dump_'"$PGDB"'.sql' fi DB_BACKUP_FILENAME=$PGDB'_'$CURRENT_DATETIME'.tar.gz' echo 'Exec pg_dump...' docker exec -t postgres pg_dump -U $PGUSER $PGDB > 'dump_'"$PGDB"'.sql' echo 'Pack to tar.gz...' tar -cf - 'dump_'"$PGDB"'.sql' | gzip -9 > "$DB_BACKUP_FILENAME" rm 'dump_'"$PGDB"'.sql' cd "$BACKUP_FOLDER" echo 'Write md5 sum...' md5sum * > MD5SUMS trap - ERR echo 'The backup of the '"$PGDB"' database was completed successfully'