Sheharyar Naseer

Regular Mongo Backups using Cron

It’s a pain configuring Cron Jobs for Database Backups of multiple apps on the same server. Sure there’s mongodump but putting it right in your crontab file doesn’t give you clean and organised backups you’d like to have. Here’s a little bash script that I use to take timestamped Mongo Backups for many of my apps.


TIMESTAMP=`date +%F-%H%M`
# mongo admin --eval "printjson(db.fsyncLock())"
# mongo admin --eval "printjson(db.fsyncUnlock())"
mkdir -p $BACKUPS_DIR
mv dump $BACKUP_NAME
View Gist on Github

First, you need to specify the name of the Database as well as your App in the MONGO_DATABASE and APP_NAME parameters.

You can also set the default storage location of the backups in the BACKUPS_DIR parameter. If you are taking backups remotely, add the details in the HOST and PORT parameters and comment/uncomment the appropriate lines. If you’d like, you can also uncomment the fsyncLock and fsyncUnlock lines, this doesn’t let the database update while the backup is being made.

After putting in values for the parameters, test if the script is working, but before that, you need to make it executable. Save it as and run:

chmod +x

If you get an error saying locale::facet::_S_create_c_locale name not valid or something else related to Locales, you need to configure them. If the backups are being stored in the specified directory, it’s now time to set up Cron. To do that, run:

sudo su
crontab -e

It’ll create a new Cron file if you haven’t already created one and open it. Enter this in a new line:

00 00 * * * /bin/bash /home/username/scripts/

Replace with the path of your script. This means that the command following * * * will be executed daily at 00 00 (12.00am).

You can also pair this script with s3cmd and store your backups on Amazon S3.