Sheharyar Naseer

Regular Mongo Backups using Cron

Open Article

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.

#!/bin/bash

MONGO_DATABASE="your_db_name"
APP_NAME="your_app_name"

MONGO_HOST="127.0.0.1"
MONGO_PORT="27017"
TIMESTAMP=`date +%F-%H%M`
MONGODUMP_PATH="/usr/bin/mongodump"
BACKUPS_DIR="/home/username/backups/$APP_NAME"
BACKUP_NAME="$APP_NAME-$TIMESTAMP"

# mongo admin --eval "printjson(db.fsyncLock())"
# $MONGODUMP_PATH -h $MONGO_HOST:$MONGO_PORT -d $MONGO_DATABASE
$MONGODUMP_PATH -d $MONGO_DATABASE
# mongo admin --eval "printjson(db.fsyncUnlock())"

mkdir -p $BACKUPS_DIR
mv dump $BACKUP_NAME
tar -zcvf $BACKUPS_DIR/$BACKUP_NAME.tgz $BACKUP_NAME
rm -rf $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 mongo_backup.sh and run:

chmod +x mongo_backup.sh
bash mongo_backup.sh

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/mongo_backup.sh

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.