Linux单机MySQL数据库自动备份

2024-01-25 11:16:45 浏览数 (2)

准备:

创建几个目录

代码语言:javascript复制
mkdir -vp mysql_backup/data mysql_backup/logs mysql_backup/scripts

data:用来存放备份数据

logs:存放脚本运行日志

scripts:存放备份脚本

1、指定数据库备份:

代码语言:javascript复制
[root@iZwz90hf9uqjtrspga3v5bZ kuliya]# cd mysql_backup/scripts/

[root@iZwz90hf9uqjtrspga3v5bZ scripts]# vim db_backup.sh

备份脚本:

代码语言:javascript复制
BACKUP_ROOT=/data/xvdb/mysql_backup    
BACKUP_FILEDIR=$BACKUP_ROOT/data       

DATE=$(date  %Y%m%d%H%M)

######备份######
db=数据库名称
echo ----------backup begin---------------------------------
mysqldump -h主机IP -uroot -p密码 -P端口 --default-character-set=utf8 -q --lock-all-tables --flush-logs -E -R --triggers -B ${db} | gzip > $BACKUP_FILEDIR/${db}_$DATE.sql.gz
echo ----------$BACKUP_FILEDIR/${db}_$DATE.sql.gz COMPLETE----------

echo "done"

-h主机ip:配置mysql的ip地址

-P端口:配置要备份的MySQL端口

----以上两项是为了防止单机MySQL配置了多个端口或者多个版本,以免出错

2、批量备份脚本:

代码语言:javascript复制
BACKUP_ROOT=/data/xvdb/mysql_backup
BACKUP_FILEDIR=$BACKUP_ROOT/data

DATE=$(date  %Y%m%d%H%M)

DATABASES=$(mysql -h主机IP -uroot -p密码 -P端口 -e "show databases" | grep -Ev "Database|sys|information_schema|performance_schema|mysql")

for db in $DATABASES
do
echo
echo ----------$BACKUP_FILEDIR/${db}_$DATE.sql.gz BEGIN----------
mysqldump -h主机IP -uroot -p密码 -P端口 --default-character-set=utf8 -q --lock-all-tables --flush-logs -E -R --triggers -B ${db} | gzip > $BACKUP_FILEDIR/${db}_$DATE.sql.gz
echo ----------$BACKUP_FILEDIR/${db}_$DATE.sql.gz COMPLETE----------
echo
done

echo "done"

配置完脚本,记得 chmod 777 backup.sh

3、配置Crontab:

代码语言:javascript复制
[root@iZwz90hf9uqjtrspga3v5bZ scripts]# crontab -e

加入

代码语言:javascript复制
*/1 * * * * /data/xvdb/mysql_backup/scripts/db_backup.sh > /data/xvdb/mysql_backup/logs/backup.log 2>&1

*/1 * * * *为Crontab定时规则,这里测试,1分钟执行一次。

然后就是等待。

查看Crontab执行情况:

代码语言:javascript复制
[root@iZwz90hf9uqjtrspga3v5bZ scripts]# tail -10f /var/log/cron
Sep 10 14:28:01 iZwz90hf9uqjtrspga3v5bZ CROND[26404]: (root) CMD (/data/xvdb/mysql_backup/scripts/db_backup.sh > /data/xvdb/mysql_backup/logs/db_backup.log 2>&1)
Sep 10 14:29:01 iZwz90hf9uqjtrspga3v5bZ CROND[26420]: (root) CMD (/data/xvdb/mysql_backup/scripts/db_backup.sh > /data/xvdb/mysql_backup/logs/db_backup.log 2>&1)

启动/关闭Crontab

代码语言:javascript复制
[root@iZwz90hf9uqjtrspga3v5bZ scripts]# /sbin/service crond stop

[root@iZwz90hf9uqjtrspga3v5bZ scripts]# /sbin/service crond start

[root@iZwz90hf9uqjtrspga3v5bZ scripts]# /sbin/service crond restart

0 人点赞