Create a directory to store backups
sudo mkdir /var/backup/db
Create a backup script and add the quoted text into the file.
sudo nano /home/root/dbbak.sh
DATE=date +"%d_%b_%Y_%H%M"
SQLFILE=/var/backup/db/db_backup_${DATE}.sql
DATABASE=<database_name>
USER=<db_user>
PASSWORD=<db_user_password>
sudo mysqldump -u ${USER} -p${PASSWORD} ${DATABASE}|gzip > ${SQLFILE}.gz
This is doing a few things;
Declaring DB Values, user & pass, using those declared values and then backing up to the /var/backup/db folder, there will be a date time stamp in the filename.
file format (i.e. db_backup_15_09_2023_10:43.sql)
If you want backups older than 7 days to automatically be removed add this at the bottom of the file
sudo find /var/backup/db/. -mtime +7 -exec rm {} ;
Save this file and continue.
To test this script use this command & then verify there’s a backup in /var/backup/db
sudo sh dbbak.sh
Now we want to check a few things as we’re being security concious at the same time.
The root user will run this as a cron job - put the file in root’s home directory and change the permissions so that only the root user can RWX - else anyone will be able to see DB creds.
Changes file owner to root
sudo chown root:root /home/root/dbbak.sh
Changes execution to allow this script to be run.
sudo chmod 700 dbbak.sh
Now we need to add this into our cron scheduler.
Log in as
root user or use sudo crontab -e
Add the following to the bottom of the file beware using sudo crontab -e puts you in a VIM window (please lookup VIM if you’ve never used it as a text editor)
0 1 * * * /home/root/dbbak.sh
This will then run at 1am server time every day.
If you can’t get on with the vim editor use
sudo nano /etc/crontab
Hope this helps.