Mongodb定时备份脚本和清除脚本

Mongodb用的是可以热备份的mongodump和对应恢复的mongorestore,在linux下面使用shell脚本写的定时备份,代码如下

1.定时备份

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/bin/bash  
sourcepath='/usr'/bin #mongodump命令所在路径
targetpath='/var/lib/mongo/mongobak' #备份存放位置
nowtime=$(date +%Y%m%d)

start()
{
${sourcepath}/mongodump -u username -p password -d dbname --host 127.0.0.1 --port 27017 --out ${targetpath}/${nowtime}
}
execute()
{
start
if [ $? -eq 0 ]
then
echo "back successfully!"
else
echo "back failure!"
fi
}

if [ ! -d "${targetpath}/${nowtime}/" ]
then
mkdir ${targetpath}/${nowtime}
fi
execute
echo "============== back end ${nowtime} =============="

2.定时清除,保留7天的纪录

1
2
3
4
5
6
7
8
9
#!/bin/bash  
targetpath='/var/lib/mongo/mongobak'
nowtime=$(date -d '-7 days' "+%Y%m%d")
if [ -d "${targetpath}/${nowtime}/" ]
then
rm -rf "${targetpath}/${nowtime}/"
echo "=======${targetpath}/${nowtime}/===删除完毕=="
fi
echo "===$nowtime ==="

3.服务器的时间要同步,同步的方法

微软公司授时主机(美国) time.windows.com
台警大授时中心(台湾) asia.pool.ntp.org
中科院授时中心(西安) 210.72.145.44
网通授时中心(北京) 219.158.14.130
调用同步: ntpdate asia.pool.ntp.org

4.设置上面脚本权限和定时任务

权限:chmod +x filename
定时任务:crontab -e

1
2
10 04 * * * /shell/mongobak.sh 1>/var/log/crontab_mongo_back.log &  
10 02 * * * /shell/mongobakdelete.sh 1>/var/log/crontab_mongo_delete.log &

每天凌晨4点10开始进行备份, 2点10分删除旧的备份

参考文章:
Mongodb定时备份脚本和清除脚本
http://www.cnblogs.com/tangnie/p/3148782.html
Linux下mysql定时备份及恢复
http://blog.csdn.net/moqiang02/article/details/37762101