Knowledge Base
0 / 4 done
0%
Beginner
~15 min
sudo required
Set Up Automated Backups with Cron and rsync
Create a backup script for files and database, then schedule it with cron to run daily.
Prerequisites
- Ubuntu server
- cron access
1
Step 1
Command
Create backup script
mkdir -p /opt/scripts /backups cat > /opt/scripts/backup.sh << 'EOF' #!/bin/bash DATE=$(date +%Y%m%d-%H%M) BACKUP_DIR=/backups # Database backup mysqldump -u root -p'YOUR_DB_PASS' --all-databases | gzip > $BACKUP_DIR/db-$DATE.sql.gz # Files backup tar -czf $BACKUP_DIR/www-$DATE.tar.gz /var/www/html # Keep only last 7 days find $BACKUP_DIR -name '*.gz' -mtime +7 -delete echo "Backup completed: $DATE" EOF chmod +x /opt/scripts/backup.sh
2
Step 2
Command
Test the backup script
bash /opt/scripts/backup.sh ls -lh /backups/
3
Step 3
Command
Schedule with cron (daily at 2 AM)
# Add to root crontab: (crontab -l 2>/dev/null; echo "0 2 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1") | crontab - crontab -l
4
Step 4
Command
Sync backups to remote server (optional)
rsync -avz --delete /backups/ backup_user@REMOTE_SERVER:/remote/backups/