07-MongoDB集群运维-自动备份

备份测试

[mongodb@mongodb01 mongo]$ cd /home/mongodb/software/mongodb-linux-x86_64-rhel70-4.2.1/bin/

[mongodb@mongodb01 bin]$ sudo ./mongodump -h 192.168.153.128:27017,192.168.153.129:27017,192.168.153.130:27017 -u dev -p 123456 -d test -o /opt/mongo/db_data_bak
2019-10-25T15:17:57.727+0800    writing test.products to 
2019-10-25T15:17:57.731+0800    done dumping test.products (7 documents)

[mongodb@mongodb01 bin]$ cd /opt/mongo/db_data_bak
[mongodb@mongodb01 db_data_bak]$ ll
总用量 0
drwxr-xr-x. 2 root root 57 10月 25 15:17 test
[mongodb@mongodb01 db_data_bak]$ 

参数说明

sudo    管理员权限执行
./mongodump 备份命令
-h 192.168.153.128:27017,192.168.153.129:27017,192.168.153.130:27017 备份地址,可填写多个副本集地址
-u dev  用户名,需针对备份库具有操作权限用户
-p 123456   用户密码
-d test 需备份库
-o /opt/mongo/db_data_bak   备份地址

开启自动备份

sudo mkdir -p /opt/mongo/mongodb_bak
sudo mkdir /opt/mongo/crontab/

编写自动执行

新建shell文件

sudo vi /opt/mongo/crontab/mongodb_bak.sh

文件中写入内容

#!/bin/bash
sourcepath='/home/mongodb/software/mongodb-linux-x86_64-rhel70-4.2.1/bin'
bakpath='/opt/mongo/mongodb_bak'
nowtime=$(date +%Y-%m-%d-%H)
username='dev'
password='123456'
dbname='test'
ip_port='192.168.153.128:27017,192.168.153.129:27017,192.168.153.130:27017'

echo "============== start backup ${nowtime} =============="
start()
{
  ${sourcepath}/mongodump -h ${ip_port} -u ${username} -p ${password} -d ${dbname} -o ${bakpath}/${nowtime}
}
execute()
{
  start
  if [ $? -eq 0 ]
  then
    echo "back successfully!"
  else
    echo "back failure!"
  fi
}
 
if [ ! -d "${bakpath}/${nowtime}/" ]
then
 mkdir ${bakpath}/${nowtime}
fi
execute
echo "============== back end ${nowtime} =============="

echo "============== start zip ${nowtime} =============="
zip -r ${bakpath}/${nowtime}.zip ${bakpath}/${nowtime}
rm -rf  ${bakpath}/${nowtime}
echo "============== zip end ${nowtime} =============="

echo "============== start delete seven days ago back ${nowtime} =============="
find ${bakpath} -type f -mtime +7 -name "*" -exec rm -rf {} \;   
echo "============== delete end ${nowtime} =============="

给文件添加可执行权限,并手动执行测试

sudo chmod +x /opt/mongo/crontab/mongodb_bak.sh

sudo /opt/mongo/crontab/mongodb_bak.sh

修改执行计划

[mongodb@mongodb01 bin]$ crontab -e     
0 0 * * * /opt/mongo/crontab/mongodb_bak.sh >/dev/null 2>&1 #每天凌晨0点0分执行备份

补充常见crontab命令

/sbin/service crond start #启动服务
/sbin/service crond stop #关闭服务
/sbin/service crond restart #重启服务
/sbin/service crond reload #重新载入配置
 
service crond status #查看crontab服务状态
service crond start #手动启动crontab服务
 
ntsysv  #查看crontab服务是否已设置为开机启动

chkconfig --level 35 crond on   #加入开机自动启动

crontab -l  #列出crontab文件
crontab -e  #编辑crontab文件
crontab -r  #删除crontab文件

你可能感兴趣的:(07-MongoDB集群运维-自动备份)