mysql,mongo备份恢复数据生产实践

一、备份数据

1.1 编写定时任务

  1. 在/etc/cron.d/backup.sh编写定时定时任务脚本
  2. 每天的2点10分执行备份mysql数据库的脚本
  3. 每天的4点10分执行备份mongo数据库的脚本
10 2 * * * root sh /backup/backup-mysql.sh
10 4 * * * root sh /backup/backup-mongodb.sh

1.2 备份脚本

1.2.1 mysql备份脚本

  1. 使用innobackupex备份mysql库的全量数据
  2. 删除超过7天的备份数据
#!/bin/sh
innobackupex --defaults-file=/etc/my.cnf --user=root --password=Mogu07550831  /backup/daily

currentFile=`ls /backup/daily | sort -rn | head -1`
historyFile=`ls /backup/daily | sort -n | head -1`

if [ "$currentFile" = "$historyFile"  ]; then
    echo "init backup"
else
    cd /backup/daily
    dirNum=`ls -l |grep "^d"|wc -l`
    if (( dirNum > 7 )); then
        echo "del $historyFile"
        rm -rf /backup/daily/$historyFile
    fi
fi

1.2.2 mongo备份脚本

  1. 使用mongodump备份指定数据库的数据
  2. 删除超过5天的备份文件
#!/bin/sh
today=`date "+%Y%m%d-%H%M"`

cd /backup/mongodb
mkdir $today
chmod -R 777 $today

mongodump --authenticationDatabase=admin -d statistics -o $today -u root -p Mogu07550831 --gzip
mongodump --authenticationDatabase=admin -d everydaykline -o $today -u root -p Mogu07550831 --gzip
mongodump --authenticationDatabase=admin -d admin -o $today -u root -p Mogu07550831 --gzip
mongodump --authenticationDatabase=admin -d evaluation -o $today -u root -p Mogu07550831 --gzip

currentFile=`ls /backup/mongodb | sort -rn | head -1`
historyFile=`ls /backup/mongodb | sort -n | head -1`

if [ "$currentFile" = "$historyFile"  ]; then
    echo "init backup"
else
    cd /backup/mongodb
    dirNum=`ls -l |grep "^d"|wc -l`
    if (( dirNum > 5 )); then
        echo "del $historyFile"
        rm -rf /backup/mongodb/$historyFile
    fi
fi

2.恢复数据

2.1 mysql恢复数据

  1. 通过innobackupex恢复备份数据
  2. 重启mysql服务
innobackupex --datadir=/var/lib/mysql --copy-back /bak/daily/2019-06-13_02-10-02/
chown -R mysql:mysql /var/lib/mysql
service mysql start

2.2 mongo恢复数据

  1. 使用mongorestore恢复制定库的数据
  2. 重启mongo服务
cd $sourcePath
unzip mongo-data-init.zip
# load init database
mongorestore -d admin --dir=$sourcePath/mongo-data-init/admin  --gzip
mongorestore -d evaluation --dir=$sourcePath/mongo-data-init/evaluation  --gzip
mongorestore -d statistic --dir=$sourcePath/mongo-data-init/statistics  --gzip
mongorestore -d everydaykline --dir=$sourcePath/mongo-data-init/everydaykline  --gzip

sleep 2s

ps -ef|grep "mongod --dbpath=/opt/data/mongodb" |grep -v grep |awk '{print $2}' | xargs kill -2

sleep 5s

cd /opt/mongodb
mongod -f conf/mongod.conf
发布了161 篇原创文章 · 获赞 40 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/qq_36441027/article/details/92805187