backup/postgres.sh

50 lines
1.2 KiB
Bash
Raw Normal View History

2024-07-11 21:18:02 +05:00
#!/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[31mSomething went wrong\033[0m"; exit 1' EXIT
set -e
export DEBIAN_FRONTEND=noninteractive
# configuration settings
POSTGRES_DB="$1"
POSTGRES_USER="$2"
CURRENT_MONTH=$(date +%Y-%m)
CURRENT_DATE=$(date +%Y-%m-%d)
CURRENT_DATETIME=$(date +%d-%b-%Y_%H_%M_%Z)
BACKUPS_PATH=/data/backups/postgres
DOCKER_SERVICE_NAME=postgres
# backup PostgreSQL database
BACKUP_FOLDER=$BACKUPS_PATH/$POSTGRES_DB
if [ ! -d "$BACKUP_FOLDER" ]; then
mkdir -p "$BACKUP_FOLDER"
fi
echo 'Creating PostgreSQL backups...'
cd "$BACKUP_FOLDER"
if [ -f 'dump_'"$POSTGRES_DB"'.sql' ]; then
rm 'dump_'"$POSTGRES_DB"'.sql'
fi
db_backup_filename=$POSTGRES_DB'_'$CURRENT_DATETIME'.tar.gz'
docker exec -t postgres pg_dump -U $POSTGRES_USER $POSTGRES_DB > 'dump_'"$POSTGRES_DB"'.sql'
tar -cf - 'dump_'"$POSTGRES_DB"'.sql' | gzip -9 > "$db_backup_filename"
rm 'dump_'"$POSTGRES_DB"'.sql'
cd "$BACKUP_FOLDER"
md5sum * > MD5SUMS
trap - EXIT
echo 'The backup of the '"$POSTGRES_DB"' database was completed successfully.'