Simple Automated Backups for MongoDB Replica Sets

There are a bunch of different methods you can use to back up your MongoDB data, but if you want to avoid downtime and/or potential performance degradation, the most common advice seems to be that you should simply do all your backups on a slave. This makes sense, since most of your queries will be hitting the primary server anyway. Unfortunately, picking a slave isn’t so simple when dealing with replica sets, because (due to automated failover) you can never really be sure which servers in the set are slaves. My workaround is to simply pick any server and then force it to be a slave before running a backup.

I do this by sticking all my backup commands in a JavaScript file (e.g. /etc/mongodb-backup.js) which starts with something like this:

1
2
3
4
5
6
7
if (rs.status()[ 'myState' ] == 1) {
   print( 'Host is master (stepping down)' );
   rs.stepDown();
   while (rs.status()[ 'myState' ] != 2) {
     sleep(1000);
   }
}

This snippet uses the rs.status() replica set command to check the current state of the local machine. If the myStatefield is “1,” then we know the machine is a primary, so we execute rs.stepDown() and wait until myState is “2” (which means the server has successfully made the transition from primary to secondary).

Next come the actual backup commands. For mongodump, something like this will work:

1
runProgram( "mongodump" , "-o" , "/mnt/backups/mongodb/" );

Alternatively, it’s possible to take backups of the raw data files. Notice that in this case, we need to sync the files to disk and disable writes first, then re-enable writes once the backup completes:

1
2
3
db.runCommand({fsync:1,lock:1}); // sync and lock
runProgram( "rsync" , "-avz" , "--delete" , "/var/lib/mongodb/" , "/mnt/backups/mongodb/" );
db.$cmd.sys.unlock.findOne(); //unlock

And finally, the whole thing can be automated by calling /usr/bin/mongo admin /etc/mongodb-backup.js from a cron job.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值