说明:生产环境中,需要对数据库定时进行备份,通常对从库配置备份。
备份的方式有:
- 直接复制mysql文件
- mysqldump
- xtrabackup等工具
配置备份脚本(mysqldump)
$ mkdir /home/mysql-bak -p
$ vim /home/mysql-bak/backup.sh
减配版
#!/bin/bash # 用户需要配置的部分 MYBACKUPDIR="/home/mysql-bak" MYUSER="test" MYPASS="test" MYHOST="localhost" MYPORT="3306" MYDBNAME="test" MYCHARSET="utf8" MYLOGIN="mysql -h$MYHOST -P$MYPORT -u$MYUSER -p$MYPASS" #MYDUMP="mysqldump -h$MYHOST -P$MYPORT -u$MYUSER -p$MYPASS -B" MYDUMP="mysqldump -h$MYHOST -P$MYPORT -u$MYUSER -p$MYPASS --default-character-set=$MYCHARSET -B" DATABASE="$($MYLOGIN -e "show databases;"|egrep -vi "Data|_schema|mysql")" # 备份指定库 MYDIR=$MYBACKUPDIR/$MYDBNAME [ ! -d $MYDIR ] && mkdir -p $MYDIR $MYDUMP $MYDBNAME|gzip >$MYDIR/${MYDBNAME}_$(date +%F).sql.gz # 备份全库全表 #for dbname in $DATABASE # do # MYDIR=$MYBACKUPDIR/$dbname # [ ! -d $MYDIR ] && mkdir -p $MYDIR # $MYDUMP $dbname|gzip >$MYDIR/${dbname}_$(date +%F).sql.gz #done
高级版
#!/bin/bash # 以下配置信息请自己修改 mysql_user="USER" #MySQL备份用户 mysql_password="PASSWORD" #MySQL备份用户的密码 mysql_host="localhost" mysql_port="3306" mysql_charset="utf8" #MySQL编码 backup_db_arr=("test") #要备份的数据库名称,多个用空格分开隔开 如("db1" "db2" "db3") backup_location=/home/mysql-bak #备份数据存放位置,末尾请不要带"/",此项可以保持默认,程序会自动创建文件夹 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!" #欢迎语 # 判断MYSQL是否启动,mysql没有启动则备份退出 mysql_ps=`ps -ef |grep mysql |wc -l` mysql_listen=`netstat -an |grep LISTEN |grep $mysql_port|wc -l` if [ [$mysql_ps == 0] -o [$mysql_listen == 0] ]; then echo "ERROR:MySQL is not running! backup stop!" exit else echo $welcome_msg fi # 连接到mysql数据库,无法连接则备份退出 mysql -h$mysql_host -P$mysql_port -u$mysql_user -p$mysql_password <$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 else echo "ERROR:No database to backup! backup stop" exit fi # 如果开启了删除过期备份,则进行删除操作 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 fi
$ chmod 777 /home/mysql-bak/backup.sh
设置定时任务
查看当前用户是否已经设置了定时执行任务
$ crontab -l
开始编写定时执行任务
$ crontab -e
将脚本的定时任务设置为每天凌晨5点执行(有可执行权限)
# m h dom mon dow command
0 5 * * * /bin/bash /home/mysql-bak/backup.sh