Easy Website Backup With Crontab
2 min read

Easy Website Backup With Crontab

Backing up your website is a good practise you should definitely adopt, your host may offer a backup of your website but I’d also recommend taking your own backups just in case your hosting providers should ever fail, plus it shouldn’t take you much of your time to configure.

You’re going to need to know your websites path, traditionally it should be located somewhere in /var/www/your-website-domain. You’re also going to need to know your username and password for the database you’re going to be backing up on your database server.

Open up crontab using the command below

sudo crontab -e

On the first line you’re going to need to specify a time to run your command, I’m going to do 00 6 * * * this means the command will run everyday at 6am, (crontab calculator if you need help) Now that you have specified a time to run your command use the line below which will backup your public folder in the directory /var/www/your-website-domain

00 06 * * * nice -n 19 /bin/tar -czf /home/username/websitebackup /www/your-website-domain_pubdata`date +\%H:\%M_\%d-\%m-\%Y`.tar.gz /var/www/your-website-domain

Remember to replace “/home/username/websitebackup” with your preferred backup location and replace “/var/www/your-website-domain” with the website you wish to backup, the result should look similar to the screen shot below.

It’s also possible to backup a database using the line below.

00 06 * * * mysqldump -u mysql_username -p[password] [database_name] | gzip -c > /home/username/database_backup/[database_name].sql.gz

You should now have both the website files and website database backed up in a directory of your choosing.

You may wish to run the command below regularly to stop your disc from filling up. This command will delete backups older than 7 days.

00 7 * * * find /path/to/backup/* -mtime +7 -exec rm {} \;

Congratulations! You now have a basic backup solution.