Posted on • Updated on

How To Automate Database Backup In CentOS

author

Kai

Step 1 - Create folders for custom scripts and database backups. 

    

$ mkdir custom_scripts
$ mkdir db_backups

Step 2 - Create .sh file

$ nano ~/custom_scripts/auto-backup.sh

Add the following content to the file:

#!/bin/bash
mysqldump -u root -p{password123} my_site_db > ~/db-backups/my_site_db_`date +"%Y-%m-%d"`.sql

Note: set password without {…}

Add the following line to delete backups that are more than 10 days old.    

find ~/db-backups -mtime +10 -type f -delete

//full script

#auto-backup.sh    

#!/bin/bash
mysqldump -u root -p{password123} my_site_db > ~/db-backups/my_site_db_`date +"%Y-%m-%d"`.sql
find ~/db-backups -mtime +10 -type f -delete

Step 3 - Set crontab   

$ crontab -e

Add the following line: 

* * * * * ~/custom_scripts/auto-backup.sh

Note: using * * * * * script will run every minute

To backup your database on daily basis Use 0 0  * * * 

TIP: https://crontab.guru/

 ⚙ Troubleshooting

To check logs :    

$ sudo cat /var/log/cron
$ sudo tail /var/log/cron

If the logs show any permissions-related errors. Make sure the script (auto-backup.sh) is executable by checking folder and file permissions.     

$ sudo chown -R $USER ~/custom_scripts   
$ sudo chmod -R 755 ~/custom_scripts

Conclusion

Some applications rely on a database to function. and possibly a database loss is required to terminate the application. We can restart our application with backup data if we have a database backup, and automatic database backup simplifies things even more. 

end of article

Related Posts

Join Our Newsletter

Want the latest & greatest from our blog straight to your inbox with some exclusive offers from our partners and sponsors?

We won't spam. Promise.