Linux系统上配置MySQL自动备份

1、编写Shell脚本,并保存为.sh文件
#!/bin/bash

# 获取当前日期和时间
current_date=$(date +%Y%m%d)
current_time=$(date +%H%M%S)

# 设置备份文件名
path="/usr/local/mysql5.7/bak"
bakFileName="dbname_backup_${current_date}_${current_time}.sql"
gzFileName="dbname_backup_${current_date}_${current_time}.tar.gz"
backup_file="/usr/local/mysql5.7/bak/dbname_backup_${current_date}_${current_time}.sql"
backup_gz_file="/usr/local/mysql5.7/bak/dbname_backup_${current_date}_${current_time}.tar.gz"


export MYSQL_PWD="123456"
# 执行备份操作
# 备份为sql文件
/usr/local/mysql5.7/bin/mysqldump -P 3306 -u root dbname > "$backup_file"
# 压缩为tar.gz
cd "$path"
tar -czvf "$gzFileName" "$bakFileName"
2、将编写好的shell文件拷贝到服务器上,授权并执行
# 授权
chmod +x db_auto_bak_mysql_sh.sh

# 执行
./db_auto_bak_mysql_sh.sh
3、编写服务脚本,并命名为backupdb.service
[Unit]
Description=Database Backup Service

[Service]
Type=simple
ExecStart=/usr/local/mysql5.7/db_auto_bak_mysql_sh.sh

[Install]
WantedBy=multi-user.target
4、编写定时timer脚本,并命名为backupdb.timer
[Unit]
Description=Database Backup Timer

[Timer]
# 设置定时器的时间间隔,例如每天0点
OnCalendar=*-*-* 00:00:00
Persistent=true

[Install]
WantedBy=timers.target
5、启动定时备份
# A.将backupdb.service和backupdb.timer文件拷贝到: 
/etc/systemd/system/

# B.执行命令(重新加载):
systemctl daemon-reload

# C.启动服务(测试是否可以正常备份):
sudo systemctl start backupdb.service

# D.启动定时任务:
sudo systemctl start backupdb.timer

# E.查看定时任务状态
sudo systemctl status backupdb.timer

成功示例:

Linux系统上配置MySQL自动备份_第1张图片

你可能感兴趣的:(linux,mysql,数据库,运维)