How to create a cronjob cPanel backup
There is no better time to create backups, well at least that’s what I personally think. Backups are important, expecially if these are databases.
In this article I’m going to explain how you can create automatic backups using cPanel Cronjobs.
So let’s get started, first go into your cPanel account in section mysql databases and create your self a mysql user. This will be used to backup your databases. For eg. you can name it “backup”.
This new user you created needs to be added to every mysql database that you want to create a backup, of course with all privileges that are needed.
Next please create a folder named backups in /home/username
In folder backups create the file dbbackup.sql.gz ; In fact, this file is an archive, just we create the archive the same way we create any other file, but with the extension .sql.gz
Now we need to create the bash script that will handle the actual backup. In my example, the bash script will be named “backup.sh” and we add the follow lines to this file:
1 2 3 4 |
#!/bin/bash date=`date +"%Y-%m-%d"`; /usr/bin/mysqldump -h localhost -u username -pDBPASS --all-databases | gzip > /home/username/backups/dbbackup_$date.sql.gz |
A little explanation may be needed … So the 3rd line of code will always save the current date in a variable to use it in the mysql backup dbbackup.sql.gz for us to always have a new backup.
The next line is the actual backup which will dump the mysql database and gzip it.
username – this is your cPanel username
backup – this the mysql user you created before
DBPASS – the mysql password used with your mysql user (If using your main cPanel user, that’s your cPanel user password)
–all-databases – we are just telling that we want to backup all databases, no changes needed here
If you want to create individual backups for each mysql databae, you can use the following code:
1 2 3 4 5 |
#!/bin/bash date=`date +"%Y-%m-%d"`; /usr/bin/mysqldump -h localhost -u username_backup -pDBPASS --databases dbname1 | gzip > /home/username/backups/dbname1_$date.sql.gz /usr/bin/mysqldump -h localhost -u username_backup -pDBPASS --databases dbname2 | gzip > /home/username/backups/dbname2_$date.sql.gz |
–databases – by this we are telling that we want a specific database
Now that we are ready with the bash script, we now need to create a cronjob which will run our script at a specific time. I set it to run every 30 minutes, but you should really run it once a day.
1 |
0,30 * * * * /bin/sh /home/username/backup.sh |
This should look similar to this picture:
That’s all, if you have any problems or you believe there’s anything else that you want me to write about, feel free to contact me.