Monday, 14 December 2015

Postgresql Database Backup to S3 | Backup script

A general script to take backup of a postgresql Database. Find it on Github, Fork it and contribute.


  • This script requires S3CMD tool installed and configured on the system from where you are running the script.
  • Postgresql installed as you need to run pg_dump command.
  • Make sure that version of your postgresql is same as version of Postgresql Host(Database to be dumped).

Steps | Procedure

After setting up  the s3cmd, lets go ahead and quickly know the steps that we are going to follow in our script.
  • Define basic variables like Postgresql database host, S3 bucket and get the system date to append to the dump file name
  • CD into a specific directory where we are going to temporary store the dump.
  • Take the dump with pg_dump
  • Upload the dump to S3
  • Remove the dump from our local system after uploading to S3

The Script


# /home/ubuntu/postgres/
# Define the variables.
echo "Get system current Date and Time..."
NOW=$(date +"%Y%m%d_%H%M%S")

# dump will be stored in /home/ubuntu/postgres/ directory
cd /home/ubuntu/postgres/;

# Taking dump
pg_dump -Fc -v -h $PGHOST -U username db_name > pg-$HOSTNAME-$NOW.dump

# Upload to S3
echo "Uploading dump to S3..."
s3cmd put /home/ubuntu/postgres/pg-$HOSTNAME-$NOW.dump s3://$BUCKET/

# Deleting the dump after uploading to S#
echo "Deleting dump..."
sudo rm pg-$HOSTNAME-$NOW.dump

pg-$HOSTNAME-$NOW.dump is the name of the dump we are going to make, you can name it like anything you want.


This is a general script which could be made more dynamic and flexible to take certain inputs from user or to check certain conditions. So if you want to contribute just fork the script and give a pull request.


Post a Comment


Copyright @ 2013 Appychip.

Designed by Appychip & YouTube Channel