mysql数据库定时备份
时间: 2023-09-15 11:20:09 浏览: 72
你可以使用MySQL自带的工具mysqldump来进行备份,并使用crontab实现定时备份。
首先,使用以下命令安装mysqldump工具:
```
sudo apt-get update
sudo apt-get install mysql-client
```
接着,创建备份脚本:
```
nano /usr/local/bin/mysql-backup.sh
```
复制以下脚本,并替换其中的数据库名、用户名、密码、备份路径:
```
#!/bin/bash
# Set the date format, filename and the directories where your backup files will be placed and which directory will be archived.
NOW=$(date +"%Y-%m-%d_%H%M%S")
FILENAME=backup-$NOW.sql
BACKUP_DIR=/var/backups/mysql
BACKUP_FILE=$BACKUP_DIR/$FILENAME
ARCHIVE_DIR=/var/backups
ARCHIVE_FILE=$ARCHIVE_DIR/mysql-backup-$NOW.tar.gz
# MySQL database credentials
DB_USER="your_username"
DB_PASS="your_password"
DB_NAME="your_database_name"
# Dump database into SQL file
mysqldump -u $DB_USER -p$DB_PASS $DB_NAME > $BACKUP_FILE
# Compress the backup file
tar -czvf $ARCHIVE_FILE $BACKUP_DIR/$FILENAME
# Remove the backup file
rm -f $BACKUP_FILE
```
保存并退出,然后赋予该脚本执行权限:
```
chmod +x /usr/local/bin/mysql-backup.sh
```
接着,使用以下命令打开crontab编辑器:
```
crontab -e
```
添加以下行,将备份脚本每天凌晨1点运行:
```
0 1 * * * /usr/local/bin/mysql-backup.sh
```
保存并退出。现在,你的MySQL数据库将在每天凌晨1点进行备份,并将备份文件压缩存档在/var/backups目录中。
阅读全文