Here is a quick and easy way to backup your files and MySQL database with a simple script:
- Create an SSH RSA Key by logging into your VPS and using the command ssh-keygen. We've used rsynckey as our filename and no passphrase.
- Create a file on your server that you will be using as your backup script. In this example we will create a file called backup.sh and placing it in /home/user/.
- In the file place the following code and edit it with your details (more information below):
mysqldump -hLOCALHOST -uDBUSERNAME -pDBPASSWORD DATABASE | gzip > /home/user/backup/DATABASE.sql.gz
tar -zcf /home/user/backup/userhome.tar.gz /home/user --exclude "/home/user/backup"
rsync -av --delete -e "ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i /home/USERNAME/.ssh/rsynckey" /home/user/backup/ USER@my.vps.com:backup - Make the script executable (chmod 0755 backup.sh).
- Create a cron job either by editing crontab manually (crontab -e) or in your control panel (cPanel, DirectAdmin, Kloxo, etc...) and set the interval to whatever you like (we recommend at least daily, but we do one every 4 hours for more current backups) for the command simply put sh /home/user/backup.sh and save.
- Wait for the backup to run and confirm there are no errors.
A breakdown of the above script:
mysqldump -hLOCALHOST -uDBUSERNAME -pDBPASSWORD DATABASE | gzip > /home/user/backup/DATABASE.sql.gz
This command will create a backup of your MySQL database in your backup directory. For more specifics on how to edit this line, please visit this link.
If you have more databases you wish to backup you can use this line as a template and add as many as you'd like to this script.
tar -zcf /home/user/backup/userhome.tar.gz /home/user --exclude "/home/user/backup"
This command will tar and compress your whole user directory except for your backup directory and save it to your backup directory.
If you have more folders or files you wish to backup you can use this line as a template and add as many as you'd like to this script.
rsync -av --delete -e "ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i /home/user/.ssh/rsynckey" /home/user/backup/ user@my.vps.com:backup
This will rsync your backup directory over to the Secure Dragon server using your SSH RSA Key. If you set a passphrase for your SSH RSA Key then you will not be able to automate this task.
If you would like to backup your data to multiple locations you can use this line as a template and add as many as you'd like to this script.