Linux system MySQL automatic backup

1. Configure automatic backup environment

1.1. Create a new folder for storing backup data in the data directory

  1. mkdir -p /data/backup/mysql
  2. #Enter the backup directory to create a mysql_backup.sh script and fill in the data
  3. vi mysql_backup.sh

1.2. Edit the mysql_backup.sh script and add the following data        

  1. #!/bin/bash
  2. #db_user= 'root'
  3. #db_password=`cat /data/www/mysql_password`
  4. #Name database
  5. db_name= 'test'
  6. #Generate the directory where the backup is stored
  7. backup_dir= '/data/backup/mysql/'
  8. #generated date
  9. current_time=$(date + '%Y-%m-%d_%H%M%S')
  10. filepath=$backup_dir$current_time '.sql.gz'
  11. #$db_password $db_user is not used here, it has been written into the configuration file
  12. echo 'Beginning to export the database...'
  13. #/etc/my.cnf This is the specific configuration file of mysql, fill in according to your actual installation path
  14. mysqldump --defaults-extra-file=/etc/my.cnf $db_name | gzip > $filepath
  15. echo 'Exported successfully, the file name is: ' $filepath

1.3. Find the mysql configuration file my.cnf and edit it

  1. [mysqldump]
  2. max_allowed_packet= 400M
  3. host= 127.0 .0 .1
  4. user=root
  5. password= 'root123' # Set as your own password, for example, mine is root123
  6. [mysql]
  7. host= 127.0 .0 .1
  8. #mysqlaccount
  9. user=root
  10. #mysqlpassword
  11. password= 'root123'

1.4 Script to increase permissions

chmod +x ./mysql_backup.sh

or

chmod u+x ./mysql_backup.sh

1.5 TEST test whether the export can be successful

  1. sh ./mysql_backup.sh
  2. # check the results
  3. ll ./mysql

2.1. Enter the following command in the terminal

  1. crontab -e
  2. #Paste the content below, you can change it according to your needs
  3. 0 1 , 12 * * * /data/backup/mysql_backup.sh # Backup data every day at 1 am and 12 noon
  4. #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
  5. */ 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

Guess you like

Origin blog.csdn.net/Shiny_boy_/article/details/128200629