Production Linux Backups: Automating Directory & Database Backups with Tar, Rsync, and Cron
Data loss incidents caused by disk corruption, failed package upgrades, or human operational errors are inevitable if reliable recovery mechanisms are not configured. A solid infrastructure backup strategy adheres to the 3-2-1 principle: three copies of critical data, across two different storage media, with at least one offsite replica.
In this guide, we will design and deploy an automated, self-pruning backup engine on Linux using tar for directory archiving, mysqldump for database exports, rsync for remote replication over SSH, and cron for unattended scheduling.
Local Staging: /var/backups/system_backups/
Archive Types: Compressed tarball (.tar.gz) + Raw SQL dump (.sql.gz)
Retention Policy: Local 7-day prune | Remote perpetual sync
Transport Layer: Rsync over encrypted SSH tunnel (Port 22)
Execution Interval: Nightly at 02:00 AM UTC via Crontab
Step 1: Install Required Utilities & Create Directory Structure
Ensure standard archive, synchronization, and database client tools are installed on your production server:
# Update package index and install tools
sudo apt update && sudo apt install -y rsync tar gzip cron mariadb-client
# Create a locked staging directory with strict permissions
sudo mkdir -p /var/backups/system_backups
sudo chmod 700 /var/backups/system_backups
sudo mkdir -p /opt/scripts
Step 2: Configure Passwordless SSH for Offsite Backups
If you plan to synchronize backups to an offsite cloud VPS, NAS, or storage box, configure an SSH key pair so rsync runs without user intervention:
# Generate a dedicated ed25519 key without a passphrase
sudo ssh-keygen -t ed25519 -N "" -f /root/.ssh/backup_key
# Copy the public key to the remote storage host
sudo ssh-copy-id -i /root/.ssh/backup_key.pub backupuser@REMOTE_BACKUP_IP
# Verify passwordless login succeeds
sudo ssh -i /root/.ssh/backup_key backupuser@REMOTE_BACKUP_IP "echo 'SSH Connection Verified'"
Step 3: Build the Unified Backup Script
Create a robust, error-tolerant bash script at /opt/scripts/server_backup.sh:
sudo nano /opt/scripts/server_backup.sh
Paste the following production script:
#!/usr/bin/env bash
set -Eeuo pipefail
# ==========================================
# CONFIGURATION VARIABLES
# ==========================================
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_DIR="/var/backups/system_backups"
LOG_FILE="/var/log/server_backup.log"
RETENTION_DAYS=7
# Source directories to protect
SOURCE_DIRS=(
"/etc"
"/var/www"
"/home"
)
# Database credentials (use .my.cnf in production for safety)
DB_USER="root"
DB_PASS="YOUR_STRONG_DB_PASSWORD"
DB_NAME="production_db"
# Remote Storage Configuration (Leave blank if local-only)
REMOTE_SYNC_ENABLED=true
REMOTE_USER="backupuser"
REMOTE_HOST="REMOTE_BACKUP_IP"
REMOTE_DEST="/mnt/storage_pool/backups/"
SSH_KEY="/root/.ssh/backup_key"
# ==========================================
# EXECUTION LOGIC
# ==========================================
log_message() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}
log_message "=== BACKUP PROCESS STARTED ==="
# 1. ARCHIVE SYSTEM DIRECTORIES WITH TAR
for DIR in "${SOURCE_DIRS[@]}"; do
if [ -d "$DIR" ]; then
SAFE_NAME=$(echo "$DIR" | sed 's|^/||; s|/|_|g')
ARCHIVE_FILE="${BACKUP_DIR}/${SAFE_NAME}_${TIMESTAMP}.tar.gz"
log_message "Archiving directory: ${DIR} -> ${ARCHIVE_FILE}"
tar -czpf "$ARCHIVE_FILE" -C / "$DIR" --exclude="*.log" --exclude="*.cache"
else
log_message "WARNING: Directory ${DIR} does not exist. Skipping."
fi
done
# 2. DUMP MYSQL / MARIADB DATABASE
if command -v mysqldump &> /dev/null; then
DB_ARCHIVE="${BACKUP_DIR}/db_${DB_NAME}_${TIMESTAMP}.sql.gz"
log_message "Exporting database: ${DB_NAME} -> ${DB_ARCHIVE}"
mysqldump -u"$DB_USER" -p"$DB_PASS" --single-transaction --quick "$DB_NAME" | gzip -9 > "$DB_ARCHIVE"
else
log_message "INFO: mysqldump not found or omitted. Skipping database backup."
fi
# 3. ROTATE & DELETE LOCAL BACKUPS OLDER THAN RETENTION LIMIT
log_message "Purging local backups older than ${RETENTION_DAYS} days..."
find "$BACKUP_DIR" -type f \( -name "*.tar.gz" -o -name "*.sql.gz" \) -mtime +$RETENTION_DAYS -exec rm -f {} \;
# 4. OFFSITE REPLICATION VIA RSYNC OVER SSH
if [ "$REMOTE_SYNC_ENABLED" = true ]; then
log_message "Initiating remote rsync replication to ${REMOTE_HOST}..."
rsync -avz --delete -e "ssh -i $SSH_KEY -o StrictHostKeyChecking=accept-new" \
"$BACKUP_DIR/" "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_DEST}"
log_message "Remote sync complete."
fi
log_message "=== BACKUP PROCESS COMPLETED SUCCESSFULLY ==="
exit 0
Step 4: Lock Down Permissions & Perform a Manual Dry Run
Because the script handles sensitive database credentials and root-owned files, lock its read and write permissions to the root user only:
# Set executable bit and restrict access
sudo chmod 700 /opt/scripts/server_backup.sh
sudo chown root:root /opt/scripts/server_backup.sh
# Run manual test execution
sudo /opt/scripts/server_backup.sh
# Verify output in staging directory and review generated logs
ls -lh /var/backups/system_backups
cat /var/log/server_backup.log
Step 5: Schedule Automated Execution via Cron
Automate execution every night at 2:00 AM UTC by adding an entry to root's crontab:
# Open root crontab editor
sudo crontab -e
Append the schedule rule to the bottom of the crontab:
# Run system and database backup every night at 02:00 AM UTC
0 2 * * * /opt/scripts/server_backup.sh > /dev/null 2>&1
Verification & Restoration Drills
An untested backup cannot be considered a valid backup. Regularly run test restorations in an isolated sandbox directory:
# Verify tarball integrity without extracting
tar -tzf /var/backups/system_backups/etc_*.tar.gz > /dev/null && echo "Tar archive is valid"
# Extract archive into a temporary test folder
mkdir -p /tmp/restore_test
tar -xzf /var/backups/system_backups/var_www_*.tar.gz -C /tmp/restore_test/
# Verify database dump extraction
gunzip < /var/backups/system_backups/db_*.sql.gz | head -n 25
Implementing this workflow ensures that in the event of hardware failure, misconfiguration, or ransomware compromise, your servers can be restored to a known good state in minutes.