}

Backup mongodb with crontab

Created:

How to backup mongodb using cron

In this tutorial we are going to explain how to do daily backups of mongodb using cron.

Step 1: Create backup script

We are going to create the following script on the home path of you logged in user:

#!/bin/bash

MONGO_DATABASE="your_db_name"
APP_NAME="your_app_name"
BACKUPS_DIR="/backup/path/backups/$APP_NAME"

MONGO_HOST="127.0.0.1"
MONGO_PORT="27017"
TIMESTAMP=`date +%F-%H%M`
MONGODUMP_PATH="/usr/bin/mongodump"
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

You need to configure:

  • MONGO_DATABASE
  • APP_NAME
  • BACKUPS_DIR

Step 2: Setup cron job using crontab

open cron editor with:

sudo su
crontab -e

Append to the end of the cron jobs a line like this one:

0 7 * * 1 /bin/bash /home/lcubo/mongo_backup.sh

The cron job will be executed every day at 7am.