Sunday, November 10, 2013

[Linux] - Automatically backup project and database @ Midnight using cron

Since the tragedy happened cause by someone, the entire server of our application "SRM" will not be recovered at all. This including the program’s source code and MySQL database. So we decided to do a daily backup of both the database and source code during 00:00:00 o’clock. This script will only work on linux server. You can use the same code. Just change certain variable value.

################################################
# Backup source code and MySQL DB
# softboxkid - 09 Mar 2012
################################################

# Please change the value of below variables:
# DO NOT CHANGE THE VARIABLE NAME.

DBNAME=your_db_name
DBPASS=your_db_password
DBUSER=your_db_user
FOLDER_NAME=the_folder_name_for_backup

DATE=`date +%Y%m%d_%H%M`

echo "Backup in progress..."
echo "Start time". $(date +%k:%M:%S)

# Step 1: prepare to backup application source code begin here.
mkdir /backup/$FOLDER_NAME-$DATE
cp /your/source_code/path -r /backup/$FOLDER_NAME-$DATE

# Step 2: prepare to backup mysql database begin here.
echo "Start time". $(date +%k:%M:%S)
mysqldump -u $DBUSER -p$DBPASS $DBNAME > /backup/$FOLDER_NAME-$DATE/$DBNAME.sql
echo "end time". $(date +%k:%M:%S)

# Step 3: prepare archive tar.gz for FOLDER_NAME
cd /backup
tar -cvf $FOLDER_NAME-$DATE.tar $FOLDER_NAME-$DATE
gzip $FOLDER_NAME-$DATE.tar

# Step 4: remove non-zip file/folder
rm -r $FOLDER_NAME-$DATE

echo "Your source code and MySQL has been backup $FOLDER_NAME-$DATE.tar.gz time finished time"
echo "end time". $(date +%k:%M:%S)

Save this code as “backup” and chmod this script to 755 and put it under /etc/cron.daily (make sure you have the root permission).
Now your daily backup will be stored in folder that you declared in step 1 of this script (in this example, it will put on folder /backup).

No comments:

Post a Comment