Skip to content

Commit 376defb

Browse files
committed
Fixed script to make a backup of postgres database
1 parent 440744c commit 376defb

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

deploy/backup_postgres.sh

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,22 @@ FILENAME="${DB_NAME}_${TIMESTAMP}.dump"
77
CONTAINER_NAME="postgres"
88
CONTAINER_TMP_RESTORE_DIR="/tmp/"
99

10-
# Load environment variables from .env file
11-
set -o allexport # Automatically exports all variables defined after this line into the environment.
12-
source .env # Loads the variables from the .env file.
13-
set +o allexport # Disables automatic export of variables.
14-
15-
# Check input parameter
10+
# Check path to backup parameter
1611
if [ -z "$1" ]; then
1712
echo "❌ Error: You must provide the path to the backup directory."
1813
echo "Usage: $0 /path/to/backup"
1914
exit 1
2015
fi
2116

17+
# Check path to backup parameter
18+
if [ -z "$2" ]; then
19+
echo "❌ Error: You must provide the database username."
20+
echo "Usage: $0 username"
21+
exit 1
22+
fi
23+
2224
BACKUP_DIR="$1"
25+
POSTGRES_USER="$2"
2326

2427
# Create folder if does not exists yet
2528
mkdir -p "$BACKUP_DIR"
@@ -28,10 +31,16 @@ mkdir -p "$BACKUP_DIR"
2831
docker exec -t "$CONTAINER_NAME" pg_dump -Fc -v -f "$CONTAINER_TMP_RESTORE_DIR$FILENAME" -U "$POSTGRES_USER" "$DB_NAME"
2932

3033
# Download backup generated
31-
docker cp "$CONTAINER_NAME:$CONTAINER_TMP_RESTORE_DIR$FILENAME" "$BACKUP_DIR"
34+
docker cp "$CONTAINER_NAME:$CONTAINER_TMP_RESTORE_DIR$FILENAME" backups
35+
36+
# Move the generated dump to the destination backup directory
37+
mv backups/"$FILENAME" "$BACKUP_DIR"
38+
39+
# Compress the generated dump
40+
gzip "$BACKUP_DIR/$FILENAME"
3241

33-
# (Optional) Remove backups older than 90 days
34-
find "$BACKUP_DIR" -type f -name "*.dump" -mtime +90 -exec rm {} \;
42+
# Remove the temp files
43+
docker exec "$CONTAINER_NAME" rm -rf "$CONTAINER_TMP_RESTORE_DIR$FILENAME"
3544

3645
# Display a success message
37-
echo "Backup done: $BACKUP_DIR/$FILENAME"
46+
echo "Backup done: $BACKUP_DIR/$FILENAME"

0 commit comments

Comments
 (0)