一、背景
生产某个小项目使用单实例MongoDB存储数据,为保障数据安全性,对其做数据备份。
二、创建备份用户
> use admin
> db.createUser({user:"dumper",pwd:"yourpassword",roles:[{role:"readAnyDatabase",db:"admin"}]})
三、备份脚本
#!/bin/bash
# 功能:mongodb数据库备份
# yousong.xiang
# 2022.1.10
# v1.0.1
# 用户授权
# use admin db.createUser({user:"dumper",pwd:"yourpassword",roles:[{role:"readAnyDatabase",db:"admin"}]})
[ -f /etc/profile ] && . /etc/profile
host=172.14.19.41
port=27017
auth_db=admin
backup_db_list='xiangys_know'
username=dumper
password=yourpassword
#备份时间
backtime=`date '+%Y%m%d%H%M%S'`
#数据备份路径
datapath='/data/mongodbbakup/bak'
if [ ! -d datapath ]; then
mkdir -pdatapath
fi
function mongodbBak {
set -eux
backup_db=1
backup_path_dir=`echo{datapath%/*}`
out_dir=`echo {datapath##*/}`
cdbackup_path_dir
mongodump \
--host="{host}" \
--port={port} \
--authenticationDatabase={auth_db} \
--db={backup_db} \
--out={out_dir} \
--username={username} \
--password={password}
cd -
set +eux
}
function compressGzip {
set -eux
backup_db=1
cd datapath
tar -czf ../{backup_db}-{backtime}.tar.gzbackup_db --remove-files
cd -
set +eux
echo "{backtime} 数据库{backup_db} 备份成功!!" >> /tmp/mongobbak.log
}
function removeGzip {
backup_path_dir=`echo {datapath%/*}`
cd{backup_path_dir:-/tmp}
find {backup_path_dir:-/tmp/mongodbbakup} -name "*.gz" -type f -mtime +7 -exec rm -rf {} \;>/dev/null 2>&1
}
function main {
for db in{backup_db_list}
do
mongodbBak db
compressGzipdb
done
removeGzip
}
main
四、写在最后
脚本会持续更新,参考地址:https://github.com/xiangys0134/deploy/blob/master/%E5%A4%87%E4%BB%BD/mongodb%E5%A4%87%E4%BB%BD/mongodbbackup.sh
留言