MongoDB backup script

Last year while I was working in a project, I needed to automate the whole backing up process from taking snapshot of the current db to saving it to AWS S3 buckets. At that time I took most of the staffs from this blog post.


Couple of days ago, I started to code for making small backup script that will backup to another cloud machine rather than to AWS S3.  Instead of  coding it from scratch, I reused my previously coded script. All I need to implement a bash function(save_in_cloud) which runs a simple scp command 🙂

The whole script look like below:

#SET the bd name which one you want to backup
#SET server path where you want to save the file
#SET your user name
#SET your host name or IP of the server
date_now=`date +%Y_%m_%d_%H_%M_%S`
current_year=`date +%Y`
log() {
echo $1
rm -rf 'db_backup_'${current_year}*
log 'cleaning up….'
log 'snapshotting the db and creating archive' && \
${MONGODB_SHELL} admin fsync_lock.js && \
log 'db locked and creating backup'
${DUMP_UTILITY} -d ${DB_NAME} -o ${dir_name} && tar -jcf $file_name ${dir_name} && \
${MONGODB_SHELL} admin fsync_unlock.js && \
log 'data backd up and created snapshot'
log 'saving backup to another server…'
scp ${file_name} ${SERVER_USER}@${HOST_NAME}:${CLOUD_PATH}
log 'saved scuccessfully'
do_backup && save_in_cloud && do_cleanup

view raw
hosted with ❤ by GitHub

I reused this script, all I did just added a new function which copy the current backup data to a remote server.  And also updated do_cleanup, now it works in any year.

The backup script depends on other two js (fsync_lock.js and fsync_unlock.js) functions which responsible for locking mongo during  db snapshots and releasing lock  after the  snapshots.

Happy Coding 🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.