定时冷备份
脚本
mysql_user="root" #MySQL备份用户
mysql_password="123456" #MySQL备份用户的密码
#mysql_host="localhost"
#mysql_port="3306"
mysql_charset="utf8" #MySQL编码
backup_db_arr=("db1" "db2") #要备份的数据库名称,多个用空格分开隔开 如("db1" "db2" "db3")
backup_location=/home/bak/mysqlbak #备份数据存放位置,末尾请不要带"/",此项可以保持默认,程序会自动创建文件夹
expire_backup_delete="ON" #是否开启过期备份删除 ON为开启 OFF为关闭
expire_days=3 #过期时间天数 默认为三天,此项只有在expire_backup_delete开启时有效
backup_time=`date +%Y%m%d%H%M` #定义备份详细时间
backup_Ymd=`date +%Y-%m-%d` #定义备份目录中的年月日时间
backup_3ago=`date -d '3 days ago' +%Y-%m-%d` #3天之前的日期
backup_dir=$backup_location/$backup_Ymd #备份文件夹全路径
welcome_msg="Welcome to use MySQL backup tools!" #欢迎语
#dbnames=$(cut -d ',' -f1-5 $backup_database)
echo "arr is (${backup_db_arr[@]})"
for dbname in ${backup_db_arr[@]}
do
echo "database $dbname backup start..."
`mkdir -p $backup_dir`
`docker exec -it mysql mysqldump -u$mysql_user -p$mysql_password $dbname --default-character-set=$mysql_charset | gzip > $backup_dir/$dbname-$backup_time.sql.gz`
flag=`echo $?`
if [ $flag == "0" ];then
echo "database $dbname success backup to $backup_dir/$dbname-$backup_time.sql.gz"
else
echo "database $dbname backup fail!"
fi
done
# 如果开启了删除过期备份,则进行删除操作
if [ "$expire_backup_delete" == "ON" -a "$backup_location" != "" ];then
#`find $backup_location/ -type d -o -type f -ctime +$expire_days -exec rm -rf {} \;`
`find $backup_location/ -type d -mtime +$expire_days | xargs rm -rf`
echo "Expired backup data delete complete!"
fi
echo "All database backup success! Thank you!"
exit
设置定时任务
## 进入定时任务设置
crontab -e
# 输入定时任务
# mysql back
0 3,13 * * /home/bin/mysql_bak.sh
0 3,13 * * 每天凌晨3点 下午1点执行一次命令
Docker使用mysqldump命令备份导出mysql容器中的数据
docker exec -it mysql01 mysqldump -uroot -proot demo > /home/bak/demo.sql
# 使用mysqldump只导出数据不导出表结构
docker exec -it mysql01 mysqldump --opt -t -uroot -proot demo > /home/bak/demo2.sql
# 使用mysqldump只导出表结构不导出数据
docker exec -it mysql01 mysqldump --opt -d -uroot -proot demo > /home/bak/demo1.sql
#使用mysqldump导出特定表的结构
docker exec -it mysql01 mysqldump -uroot -proot -B demo --table playmath_user > /home/bak/playmath_user.sql
# Docker执行导入(恢复)数据库命令:
docker exec -i mysql01 mysql -uroot -proot 库名 < /home/bak/playmath_sso.sql
参考: