Easy Way to Auto Backup Your Linux

Data is one thing that is very important for us. Data loss is a disaster for everyone, including a System Administrator. Therefore, it is necessary to backup your data regularly. In Linux we can easily to backup data automatically and scheduled. The following will explain how.

Step 01 - setup ssh

This step should be done because we will upload the backup file to a remote server. At this stage we will arrange to login SSH without password.

Create RSA key:

mkdir -p ~/.ssh
touch ~/.ssh/authorized_keys
ssh-keygen -t rsa -b 2048
chmod go-w ~/
chmod 700 ~/.ssh
chmod 600 ~/.ssh/*

Upload public key to backup server:

ssh-copy-id -i ~/.ssh/id_rsa.pub '-o StrictHostKeyChecking=no REMOTEUSER@REMOETHOST -pREMOTEPORT'

Create backup directory in local and remote server:

mkdir -p /var/backup
chown -R REMOTEUSER /var/backup
ssh REMOTEUSER@REMOETHOST -pREMOTEPORT 'sudo mkdir -p /var/backup ; sudo chown -R REMOTEUSER /var/backup'

Step 02 - install backup2l

In RedHat based distros:

yum update
yum install backup2l

In Debian based distros:

apt-get update
apt-get install backup2l

Or you can build it from source. Please read the official documentation for more information.

Step 03 - configure backup2l

Edit /etc/backup2l.conf and create configuration like this:

FOR_VERSION=1.5  
VOLNAME="all"  
SRCLIST=(/etc/apache2/sites-available /home)  
SKIPCOND=(-path "/home/REMOTEUSER" "/etc/apache2/sites-available/default*" "*.nobackup*" -o -name "*.o")  
BACKUP_DIR="/var/backup"  
MAX_LEVEL=3  
MAX_PER_LEVEL=9  
MAX_FULL=2  
GENERATIONS=1  
CREATE_CHECK_FILE=1  
AUTORUN=0  
SIZE_UNITS="M"  
UNCONFIGURED=0  
CREATE_DRIVER="DRIVER_TAR_GZ"  
PRE_BACKUP () {  
  echo -e "  Backup MySQL Databases:"
  echo -e "  -----------------------"
  /usr/bin/mysqldump -u root -p --all-databases --skip-lock-tables | bzip2 > /home/all_db.sql.bz2
}
POST_BACKUP () {  
  echo -e "  Uploading Backup File to Backup Server:"
  echo -e "  ---------------------------------------"
  /usr/bin/scp -r /var/backup/all.*.tar.gz REMOTEUSER@REMOTEHOST:/var/backup/.
}

Create Cron for auto backup, in this example I just create automatic backup every week. You can edit as you want.

cat > /etc/cron.d/autobackup <<EOF  
@weekly /usr/sbin/backup2l > /dev/null || nice -n 19 ionice -c 3 backup2l -b
EOF  

Notes: You can modify the configuration as you want. Remember to change REMOTEUSER, REMOTEHOST, and REMOTEPORT variables.

References:

Official backup2l

Hetzner Wiki

Done. That's easy huh? Thank you for reading

Halo, saya adalah seorang pengajar dan pengembang aplikasi, khususnya aplikasi web. Profil saya dapat ditemukan di Twitter dan Github.