Cronjob For Databse Backup and Application Files Backup
We will discuss about writing cronjob for taking application folder backup as well as taking backup of database files/data. We have used shell script to automate the whole process.
- Taking Application Folder Backup
Below are the command which will take folder backup
TIME=`date +%b-%d-%Y`
FILENAME=backup-$TIME.tar.gz
SRCDIR=/var/www/html/sourceDirName
DESDIR=/var/app_data_backup/DestinationDirName
tar -cpzf $DESDIR/$FILENAME $SRCDIR
Above command is very simple. You have to define your source directory and destination directory and tar command will put files in destination folder.
2. Taking Mysql Database Backup
Below is the command for taking mysql db backup
user=”root”
password=”DBPassword”
host=”localhost”
db_name=”DBName”
# Other options
backup_path=”/var/destinationfoldername”
date=$(date +”%d-%b-%Y”)
# Set default file permissions
umask 177
# Dump database into SQL file
mysqldump — defaults-extra-file=”/var/.my.cnf” -u root $db_name > $backup_path/$db_name-$date.sql
So for mysql database backup, you have to mention your db name, password, host, db name and backup path. After that we are generating unique number with the help of date and time for file. We also need one .my.cnf file. Please refer below repository location for this.
3. Taking PostgreSQL Database Backup
Below is the command for taking PostgreSQL db backup
pg_dump -U postgres — format=c — file `date +%F-%H%M%S`_backup.sqlc DatabaseName
Now in this case you have to create pgpass file under /root directory for automatic backup.
Please refer below repository for the same
Also there are many other things we can do in our cronjob like sending mail once backup is done and many others but this will help you to get started and then you can extend it as per your need. Also please make sure once you have created your shell script file please create cronjob using crontab -e command and please set your cronjob as per your requirements.