Scheduling Automated VPS Backup

Some time you will need your data if your data lost and it would be your nightmare if happened. but you can prevent that thing if you do a simple move on your VPS such as back up you data and make a schedule for certain time, you can make a daily, montly or even yearly.

I do this thing using SSH and here is a simple command line to walk through

Create a Directory/folder to back up :

mkdir backup

Create file backup.sh

nano backup.sh

And fill you GNU / code with these :

#!/bin/sh
 
WEBSITE="yourwebsite.com"
DATABASE="databasename"
USER="admin"
PASSWORD="123456"
TANGGAL=`date +%d%m%y`
 
# Backup file website
tar fczP /root/backup/backup_${WEBSITE}_${TANGGAL}.tar -C / var/www/html
 
# Backup database
mysqldump --add-drop-table -u $USER -p${PASSWORD} $DATABASE | gzip > /root/backup/backup_${DATABASE}.sql.gz
 
# Erasing file backup that more than 3 days ago
find /root/backup/backup_* -mtime +3 -exec rm {} \;

Explanation

  • /root/backup is folder that you create in the first step, where is your file backup will along with database will create archive tar and compress with gzip and save.
  • /var/www/html is a folder for virtual host or directory of your website that you want to back up.
  • And the last line is back up files that more than 3 days ago will expired and erased from your server automatically ” -mtime +3 -exec rm {} \ ” .

CHMOD

To execute your backup.sh you need to chmod command and it would be like :

chmod +x backup.sh

Create Back Up Schedule

We will use cron function to create scheduling our backup so that backup.sh can exucute in a time that you set previously, here is an example that execute in every 2 A.M

crontab -e

And also add this line

0 02 * * * /root/backup.sh

save it and done.

Let’s try it.

Leave a Comment