setting up automatic backups on linux
Setting Up Automatic Backups on Linux: A Complete Guide
Introduction Automatic backups are essential for data protection on Linux systems. By automating processes, you reduce human errors and guarantee consistent data protection. This article covers practical methods for both beginners and advanced users, from simple scripts to advanced tools.
Basic Backups with Cron and Scripts
Cron as the Backbone
Cron is the standard task scheduler in Linux for recurring tasks. A typical backup system starts with a bash script scheduled via cron. For example:
0 3 * /usr/local/bin/backup.sh
This runs a backup daily at 3:00 AM. Logging (>> /var/log/backup.log) is crucial for troubleshooting.
Simple TAR Script
A minimal backup script archives directories with tar:
tar -czf /backups/$(date +%Y%m%d).tar.gz /important_data
Combine this with `find ... -mtime +7 -delete` for automatic cleanup of old backups.
Database Backups
MySQL/MariaDB Backups
For databases, a specific approach is needed. `mysqldump` is the standard tool:
mysqldump -u root -p password database > backup.sql
Best practice is to compress this (gzip) and place credentials in a protected .my.cnf file.
Advanced Tools
Rsync for Efficiency
Rsync only synchronizes changed files, ideal for frequent backups:
rsync -avz --delete /data/ backup_server:/backups/
Important options:
- `-a`: archive mode (preserve permissions)
- `--delete`: delete files removed at the source
- `--exclude`: exclude temporary directories
RSnapshot for Versioning
Rsnapshot combines rsync with hardlinks for multiple backups with minimal space:
rsnapshot daily
Configure retention in /etc/rsnapshot.conf (e.g., daily 7, weekly 4).
Security and Storage
Encryption
Use `gpg` for sensitive backups:
tar -cz /data | gpg -c > backup.tar.gz.gpg
Remote Backups Always follow a 3-2-1 strategy: - 3 copies - 2 different media - 1 offsite backup
For example via SSH:
rsync -e "ssh -i /path/to/key" -avz /data user@remote:/backups/
Practical Tips
1. Test recovery procedures - A backup without a test is worthless 2. Monitor logs - Set up alerts for failed jobs 3. System files - Use `--one-file-system` for full system backups 4. Storage management - Automate space checks with scripts
Conclusion Whether you choose simple cron jobs or advanced solutions like Bareos, consistency is key. Combine tools as needed and adjust retention periods based on your data criticality. Start small but think big - any backup is better than no backup.