1. 前言
由于线上的mongodb 数据体量越来越大,如果没有完善的备份方案,发生故障势必造成业务很长时间的暂停。参考了网上方案,写出以下总结和备份方案:
备份方案分为两种:全备和增量备份,二者结合起来使用。
参考链接:https://www.cnblogs.com/xuliuzai/p/9917137.html 感谢作者的分享。
2. 构建mongodb 副本集测试环境
首先在测试环境进行测试,过程如下:
测试机:192.168.118.16 系统:CentOS 7
首先搭建mongodb 副本集(为了和线上环境保持一致)这里使用 mongodb 3.6 的版本,建议和生产环境相同的版本。
Mongdb 没啥安装的, 开箱即用。副本集参考链接:https://www.cnblogs.com/hukey/p/5769548.html
rs0:PRIMARY> rs.isMaster(); { "hosts" : [ "192.168.118.16:27017", "192.168.118.16:27018", "192.168.118.16:27019" ], … …
副本集创建成功。
接下来,向集群里写入数据:
rs0:PRIMARY> for(var i=1;i<=10000;i++) db.users.insert({id:i, name:"hukey",city:"xi'an"}); WriteResult({ "nInserted" : 1 }) rs0:PRIMARY> show dbs; admin 0.000GB config 0.000GB local 0.000GB test 0.000GB rs0:PRIMARY> use test switched to db test rs0:PRIMARY> db.users.count(); 10000
写入了 1W 条数据。
准备工作完成。
3. mongodb 全量备份及恢复
全备脚本 [ mongodb_back_all.sh ] 如下:
#!/bin/bash # Author:hukey host='192.168.118.16' port='27017' sourcepath='/mongodb/bin' targetpath='/mongodb/backup' nowtime=$(date "+%Y%m%d") start(){ $sourcepath/mongodump --host $host --port $port --oplog --gzip --out ${targetpath}/${nowtime} } execute(){ echo "=========================$(date) backup all mongodb back start ${nowtime}=========" start if [ $? -eq 0 ];then echo "The MongoDB BackUp Successfully!" else echo "The MongoDB BackUp Failure" fi } if [ ! -d "${targetpath}/${nowtime}" ];then mkdir -p "${targetpath}/${nowtime}" fi execute backtime=$(date -d '-7 days' "+%Y%m%d") if [ -d "${targetpath}/${backtime}/" ];then rm -rf "${targetpath}/${backtime}/" echo "=======${targetpath}/${backtime}/===删除完毕==" fi echo "========================= $(date) backup all mongodb back end ${nowtime}========="
全库还原脚本 [ mongodb_restore_all.sh ] 如下:
#!/bin/bash # Author:hukey echo -e "\033[31;1m*****[ Mongodb ] 全库恢复脚本*****\033[0m" host=192.168.118.16 mongo_bin=/mongodb/bin/ backpath='/mongodb/backup' echo -e "\033[32;1m[ 选择要恢复全库的日期 ] \033[0m" for backfile in `ls $backpath`; do echo $backfile done read -p ">>>" date_bak if [[ $date_bak == "" ]] || [[ $date_bak == '.' ]] || [[ $date_bak == '..' ]]; then echo -e "\033[31;1m输入不能为特殊字符.\033[0m" exit 1 fi if [ -d $backpath/$date_bak ];then read -p "请确认是否恢复全库备份[y/n]:" choice if [ "$choice" == "y" ];