This article describes an easy way to backup a Postgres database to Amazon S3 using s3cmd and crontab in Linux environment.
Install S3cmd
S3cmd is a command-line utility for managing data in AWS S3.
For Debian/Ubuntu
apt-get install s3cmd
For RedHat/CentOS
yum install s3cmd
For OSX
brew install s3cmd
Set Amazon access id & secret keys using the --configure option. Enable encryption for data transferring as well as HTTPS.
s3cmd --configure
Backup the database
pg_dump -v --format=c -h localhost -U YOUR_USER YOUR_DB > backup.dump
Push to S3
s3cmd put backup.dump s3://YOUR_BUCKET_NAME --encrypt
Automate the process
Create a new bash file in the root directory.
#!/usr/bin/env bash
DB_NAME=$1
DB_USER=$2
DB_PASS=$3
BUCKET_NAME=<YOUR_NAME_HERE>
TIMESTAMP=$(date +%F_%T | tr ':' '-')
TEMP_FILE=$(mktemp tmp.XXXXXXXXXX)
S3_FILE="s3://$BUCKET_NAME/backup-$TIMESTAMP"
PGPASSWORD=$DB_PASS pg_dump -Fc --no-acl -h localhost -U $DB_USER $DB_NAME > $TEMP_FILE
s3cmd put $TEMP_FILE $S3_FILE --encrypt
rm "$TEMP_FILE"
Change file permission to be executable using chmod +x and test the file using:
./FILE_NAME.sh DATABASE_NAME USER_NAME DATABASE_PASSWORD
It should upload the backup to the S3 configured earlier.
Attach to a cron job
crontab -e
Edit the file to execute the script at (say) every sunday at midnight:
0 0 * * 0 /home/ubuntu/FILE_NAME.sh DATABASE_NAME USER_NAME DATABASE_PASSWORD
Save the file and check the cron logs in /var/log/syslog file.
Top comments (6)
Thanks for the share!
Same way one can automate the backups for MySQL — using
mysqldump.yeap, I do exactly the same :) Having a
bash scriptwithmysqldumpand then upload to s3.Our Complete Automation Template
crontabmysqldump) to make backupphp) to sync backup withGoogle Cloud Storagephp) for Slack notification to our dev teamHi, thank you for the article.
Are there any benefits of using
s3cmdover standardaws-cliutility which hasaws s3 cpcommand?I installed postgress through caprover(I have a docker based postgress), so what do you suggest?
can you add a post on how to backup elasticache redis using the same technique