DEV Community

Cover image for Bash script that create a backup of a PostgreSQL database
Muzaffar khan
Muzaffar khan

Posted on

Bash script that create a backup of a PostgreSQL database

This script is used to create a backup of a PostgreSQL database running in a Docker container, and then upload that backup to an Amazon S3 bucket.

#!/bin/bash
DB_CONTAINER_NAME=""
DB_NAME=""
DB_USER=""

S3_BUCKET_NAME="<BUCKET_NAME>/<FOLDER>/"

TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILE="$DB_NAME-$TIMESTAMP.sql"

docker exec -i $DB_CONTAINER_NAME pg_dump -U $DB_USER -d $DB_NAME > $BACKUP_FILE

aws s3 cp $BACKUP_FILE s3://$S3_BUCKET_NAME

rm $BACKUP_FILE

echo "Backup completed and uploaded to S3: s3://$S3_BUCKET_NAME$BACKUP_FILE"
Enter fullscreen mode Exit fullscreen mode

PostgreSQL Container Details:

  1. DB_CONTAINER_NAME: The name of the PostgreSQL Docker container.
  2. DB_NAME: The name of the database to be backed up.
  3. DB_USER: The PostgreSQL user used to access the database.

S3 Bucket Details:

  1. S3_BUCKET_NAME: The name of the Amazon S3 bucket where the backup will be uploaded.

Note: Make sure that aws cli installed on your system.

Top comments (0)