首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Simple Automated Backups for MongoDB Replica Sets

Simple Automated Backups for MongoDB Replica Sets

作者头像
全栈程序员站长
发布2022-01-04 09:51:26
发布2022-01-04 09:51:26
3890
举报

大家好,又见面了,我是全栈君,今天给大家准备了Idea注册码。

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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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.

版权声明:本文博客原创文章,博客,未经同意,不得转载。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/117615.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档