Better MongoDB backup script with Tar and move to S3 Bucket

Theo van der Sluijs

Published on Aug 11, 2015

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

A few months ago I wrote a article about a MongoDB backup script.

It worked, but after a while it became useless because it kept locking mynMongoDB server. And with that lock it did not open it afterwards so my sites just crashed.

This happend because the MongoDb was just to big to handle within a reasonablentime. So I had to write another MongoDB backups script.

This script, creates a backup from any MongoDB database, turns it into a tarnfile and moves it to any Amazon S3 environment.

MongoDB Backups script

The script is pretty straight forward. Just change the [vars] and you cannbackup your MongoDB!

#!/bin/bash
#add right params at [PARAM]
export LC_ALL=C

BAK="/opt/backup"

TIMESTAMP=`date +%F-%H%M`
S3_BUCKET_NAME=[BUCKET_NAME]
S3_BUCKET_PATH=[BUCKET_PATH]

MONGO_DBNAME=[MONGO_DBNAME]

#creating mongo backup
/usr/bin/mongodump --port 27017 --db $MONGO_DBNAME --out $BAK/$MONGO_DBNAME-$TIMESTAMP

#tar the backupsfiles
tar cf $BAK/$MONGO_DBNAME-$TIMESTAMP.tar $BAK/$MONGO_DBNAME-$TIMESTAMP

#put the files on S3
s3cmd put $BAK/$MONGO_DBNAME-$TIMESTAMP.tar s3://$S3_BUCKET_NAME/$S3_BUCKET_PATH/$MONGO_DBNAME-$TIMESTAMP.tar

#delete 2 days old backups on your server
find $BAK/*.tar -mtime +2 -exec rm {} \;

Have fun using it!

 
Share this