Bash
1 前言
最近需要备份MongoDB,于是定制适用于自己环境的脚本。
2 最佳实践
2.1 环境部署
MongoDB yum部署,
MongoDB二进制部署,
MongoDB Docker 部署,
2.2 部署备份脚本
2.2.1 创建备份脚本
mkdir -p ~/scripts/ vim ~/scripts/backupMongodb.sh
可加入如下配置,
#!/bin/bash backupStorageDIR="/backup/mongodb" dumpName="mongodb-"`date +'%Y%m%d%H%M%S'` logFile="/var/log/mongodbBackup.log" logDataTime=`date +"%Y-%m-%d %H:%M:%S"` dailyBakKeeptime='+30' weeklyBakKeeptime='+365' Today="`date +%a`" dailyBakDIR=$backupStorageDIR"/dailyBackup" weeklyBakDIR=$backupStorageDIR"/weeklyBackup" cd $backupStorageDIR if [ $? != 0 ]; then echo $logDataTime" Directory mount error!" | tee -a $logFile exit 1 fi case $Today in Mon|Tue|Wed|Thu|Fri|Sat) mkdir -p $dailyBakDIR"/"$dumpName if [ ! -d $dailyBakDIR"/"$dumpName ]; then echo $logDataTime" dumpName not found!" | tee -a $logFile exit 1 fi mongodump -o $dailyBakDIR"/"$dumpName sleep 10 cd $dailyBakDIR tar --remove-files -cvjf $dumpName".tar.bz2" $dumpName #find $dailyBakDIR -type f -name mongodb-\*.tar.bz2 -ctime $dailyBakKeeptime -exec ls {} \; find $dailyBakDIR -type f -name mongodb-\*.tar.bz2 -ctime $dailyBakKeeptime -exec rm -f {} \; ;; Sun) mkdir -p $weeklyBakDIR"/"$dumpName if [ ! -d $weeklyBakDIR"/"$dumpName ]; then echo $logDataTime" dumpName not found!" | tee -a $logFile exit 1 fi mongodump -o $weeklyBakDIR"/"$dumpName sleep 10 cd $weeklyBakDIR tar --remove-files -cvjf $dumpName".tar.bz2" $dumpName #find $weeklyBakDIR -type f -name mongodb-\*.tar.bz2 -ctime $weeklyBakKeeptime -exec ls {} \; find $weeklyBakDIR -type f -name mongodb-\*.tar.bz2 -ctime $weeklyBakKeeptime -exec rm -f {} \; ;; esac
– 变量“backupStorageDIR”定义备份存储的目录,本例为”/backup/mongodb”
– 变量“logFile”定义备份日志的路径,本例为”/var/log/mongodbBackup.log”
– 变量“dailyBakKeeptime”定义日备份保留的时间,本例为’+30’,即保留30天
– 变量“weeklyBakKeeptime”定义周备份保留的时间,本例为’+365’,即保留365天
– 变量“dumpName”定义mongodb的备份文件夹名称,本例为”mongodb-“`date +’%Y%m%d%H%M%S’`
– 变量“logDataTime”定义日志的时间格式,本例为`date +”%Y-%m-%d %H:%M:%S”`
2.2.2 配置脚本触发
crontab -e
加入如下配置,
0 2 * * * bash ~/scripts/backupMongodb.sh
参阅文档
==============
https://docs.mongodb.com/manual/reference/program/mongodump/
没有评论