Simple MongoDB backup script

Backups are very important. It’s very easy to mess up your server.
Here’s how to set up automatic backups for MongoDB

1. Get MongoDB tools

  • Go to https://www.mongodb.com/try/download/database-tools, pick your distro (in this guide I use Ubuntu), select the deb format, and click copy link
  • SSH into your server and type these commands:
wget -O mongotools.deb <your link you copied>
sudo apt install ./mongotools.deb

2. Verify mongodb tools is installed

mongorestore --version

If that command returns output, congratulations. You have successfully installed the required mongodb tools.

3. Make the script

First off, cd into the directory you want to use. I recommend backing up to a NAS server or a hard drive, however an SSD is fine too just a bit of a waste of fast storage space. Replace the path /path/to/backups with your own.

Now let’s open the file.

sudo nano backup.sh

Paste in the following contents:

#!/bin/bash

cd /path/to/backups
current_date_time=$(date +%Y/%m/%[email protected]%H-%M-%S)
file=backup-$current_date_time
echo "MongoBackup starting"
echo Using date: $current_date_timeecho "Starting mongodump..."
mongodump --uri="mongodb://yourusername:yourpassword@dbhost:27017/?authSource=admin" --out $file
echo "MongoDump done"

Now there are a few things you need to modify:

  • yourusername: set to a mongoDB user that can access all databases
  • yourpassword: the password for the mongoDB user
  • /path/to/backups: the path you want to store your backups in
  • dbhost: the mongodb host, typically localhost unless you are backing up from another machine

You also may want to modify the mongodb uri to your setup accordingly
We also need to grant execute permission to the script:

sudo chmod +x ./backup.sh

4. Let’s test it

./backup.sh

If everything goes correct, you should see a backup directory created and inside of it some folders to group the backups by date.

5. Finally, automate it

We can use crontab to automatically execute it on a schedule
While I won’t go into too much detail about crontab in this post, you can use crontab.guru to figure out the syntax. I will go with every day at 12:05, so that will be 5 12 * * *

To add the crontab execute crontab -e
You should pick the nano text editor as it’s the easiest
Add a cron job at the end of the file like so:

5 12 * * * /path/to/backups/backup.sh 

Replace my 5 12 * * * with your own cron job syntax if you want to run it at a different time. Save and exit. Now the cron job should run properly

A couple of notes:

  • You may wanna set your backups folder to only be accessible by root, because your backup.sh file contains the mongoDB password. If you do that, use sudo crontab -e instead
  • You may wanna use a mongoDB user that only has read access to the database

Leave a comment

Your email address will not be published. Required fields are marked *