docker mysql数据库自动备份代码:

创建工作目录mkdir /home/backup,指定目录下创建脚本vi /home/backup/mysql_backup.sh,添加如下内容,并赋予其可执行权限。chmod +x mysql_backup.sh

#!/bin/bash

# MySQL容器名称
MYSQL_CONTAINER_NAME="your_mysql_container_name"

# MySQL用户和密码
MYSQL_USER="your_mysql_user"
MYSQL_PASSWORD="your_mysql_password"

# 备份文件保存目录
BACKUP_DIR="/path/to/backup/directory"

# 获取当前日期
CURRENT_DATE=$(date +"%Y-%m-%d")

# 创建备份文件名
BACKUP_FILE_NAME="mysql_backup_${CURRENT_DATE}.sql"

# 进行数据库备份
docker exec ${MYSQL_CONTAINER_NAME} sh -c "exec mysqldump --all-databases -u${MYSQL_USER} -p${MYSQL_PASSWORD}" > "${BACKUP_DIR}/${BACKUP_FILE_NAME}"

# 压缩备份文件
gzip "${BACKUP_DIR}/${BACKUP_FILE_NAME}"

# 输出备份结果
if [ $? -eq 0 ]; then
  echo "MySQL backup successfully completed on ${CURRENT_DATE}"
else
  echo "MySQL backup failed on ${CURRENT_DATE}"
fi
# 删除30天前的旧备份文件
find ${BACKUP_DIR} -name "mysql_backup_*.sql.gz" -type f -mtime +30 -exec rm {} \;

最后定义定期执行此脚本:

crontab -e

0 0 /5 * /path/to/mysql_backup.sh