Automated backup using Cronjobs
Task
Configuring automated backups using Cronjobs on a linux webserver.
Explanation
Log in to the server with Putty (or similar SSH client)
open crontab using the following command:
crontab -e
Enter insert mode by typing:
i
Type the following entry:
30 * * * * /full/path/to/shell-script/backup.sh
press "esc" key, then type:
:wq
What does all this do?
30 * * * * /full/path/to/shell-script/backup.sh
the beginning of this line indicates minutes, hours, days, months and weekdays.
An asterisk stands for all.
So this script will run at 30 minutes past the hour every hour of every day.
The script path is the full path (on a shared server this will be something like /homepages/23/htdocs/…/ On a dedicated server it might be something like: /www/vhosts/domain/httpdocs/…)
This script is where we will put some shell script that will actually be executed when the cronjob runs.
So now lets create the script
Open a text editor of your choice (I use Alleycode) and enter the script you want to run, I use something like the following:
# get current date as a variable
CURRENTDATE=$(date +%d%m%Y)
# navigate to database file directory
cd /fullpath/to/backupfiles/htdocs/directory/etc/
# backup all files without full trailing directory data – this command prevents tar from
putting the files into recursive directories –
it makes it easier to restore it back to its current folder
tar cfz files$CURRENTDATE.tar.gz ./*
# move the backup file to our backups storage location
mv files$CURRENTDATE.tar.gz /fullpath/to/backupfiles/htdocs/directory/etc/backups/
# goto that location
cd /fullpath/to/backupfiles/htdocs/directory/etc/backups
# backup the database
mysqldump -hDATABASEHOSTNAME -uDATABASEUSERNAME -pPASSWORD
DATABASENAME > database$CURRENTDATE.sql
Save this file as backup.sh (Or whatever you are calling in the cronjob) – if you are using an editor like notepad, make sure it doesnt apend .txt to the file (this is easy to avoid by typing:
"backup.sh"
upload this file to the location you specified when creating the cronjob.
Once uploaded, we need to make the script executable, issue this command at the shell to achieve this:
chmod u+x script.sh
Now we are all setup, to test the file you can type:
sh script.sh
And press enter at the shell prompt, this will run the script so you can check that it works.
Thanks
N/a