定时备份docker容器中mysql的数据

echo '开始备份数据'
 
now=$(date "+%Y%m%d")
backup_dir="/data/back_up"
 
#获取容器id
mysqlid=`/usr/local/bin/docker ps -aqf "name=mysql5.7"`
 
#进入mysql容器
/usr/local/bin/docker exec -i ${mysqlid} bash<<'EOF'
 
#mysqldump导出表结构和数据
if [ ! -d "/backup" ]; then
    mkdir -p /backup
fi
 
if [ -f "/backup/db.sql" ]; then
    rm -rf /backup/db.sql
fi
 
mysqldump --single-transaction -u root -h 127.0.0.1 --password=123456 --all-databases > /backup/db.sql
 
echo '成功制作备份sql'
 
if [ $? -ne 0 ]; then
    echo 'mysqldump运行失败'
    exit
    EOF
fi
 
exit
 
EOF
 
#将容器内sql文件导出到服务器
if [ ! -d "${backup_dir}" ]; then
    mkdir -p "${backup_dir}"
fi
 
/usr/local/bin/docker cp ${mysqlid}:/backup/db.sql ${backup_dir}/db_${now}.sql
 
if [ $? -ne 0 ]; then
    echo 'docker cp文件失败'
    exit
fiecho '完成备份数据'

 

posted @ 2021-11-30 14:43  屁桃  阅读(717)  评论(0编辑  收藏  举报