1. Configure automatic backup environment
1.1. Create a new folder for storing backup data in the data directory
-
mkdir -p /data/backup/mysql
-
#Enter the backup directory to create a mysql_backup.sh script and fill in the data
-
vi mysql_backup.sh
1.2. Edit the mysql_backup.sh script and add the following data
-
#!/bin/bash
-
#db_user= 'root'
-
#db_password=`cat /data/www/mysql_password`
-
#Name database
-
db_name= 'test'
-
#Generate the directory where the backup is stored
-
backup_dir= '/data/backup/mysql/'
-
#generated date
-
current_time=$(date + '%Y-%m-%d_%H%M%S')
-
filepath=$backup_dir$current_time '.sql.gz'
-
#$db_password $db_user is not used here, it has been written into the configuration file
-
echo 'Beginning to export the database...'
-
#/etc/my.cnf This is the specific configuration file of mysql, fill in according to your actual installation path
-
mysqldump --defaults-extra-file=/etc/my.cnf $db_name | gzip > $filepath
-
echo 'Exported successfully, the file name is: ' $filepath
1.3. Find the mysql configuration file my.cnf and edit it
-
[mysqldump]
-
max_allowed_packet= 400M
-
host= 127.0 .0 .1
-
user=root
-
password= 'root123' # Set as your own password, for example, mine is root123
-
[mysql]
-
host= 127.0 .0 .1
-
#mysqlaccount
-
user=root
-
#mysqlpassword
-
password= 'root123'
1.4 Script to increase permissions
chmod +x ./mysql_backup.sh
orchmod u+x ./mysql_backup.sh
1.5 TEST test whether the export can be successful
-
sh ./mysql_backup.sh
-
# check the results
-
ll ./mysql
2.1. Enter the following command in the terminal
-
crontab -e
-
#Paste the content below, you can change it according to your needs
-
0 1 , 12 * * * /data/backup/mysql_backup.sh # Backup data every day at 1 am and 12 noon
-
#You can use the following as a test first, run it once a minute, we only need to check the folder ll /data/backup/mysql
-
*/ 1 * * * * /data/backup/mysql_backup.sh
2.2, crontab stop and start commands
Start: /sbin/service crond start
Stop: /sbin/service crond stop
Reload: systemctl reload crond.service
Restart the service: systemctl restart crond.service
View status: systemctl status crond.service