Server Administration
Automated Server Backups with Cron Jobs
Backups are useless if you forget to make them. Automating them with cron ensures you always have a recent copy, even if something goes wrong at 3 AM.
1. Create a Backup Directory
bash
sudo mkdir -p /opt/backups
sudo chmod 700 /opt/backups2. Write a Backup Script
bash
sudo nano /opt/backups/backup.shPaste the following script. It creates a timestamped archive and also dumps your MariaDB databases:
bash
#!/bin/bash
TIMESTAMP=$(date +"%Y-%m-%d_%H-%M")
BACKUP_DIR="/opt/backups"
RETENTION_DAYS=7
# --- File Backup ---
# Add your important directories here
tar -czf "$BACKUP_DIR/files_$TIMESTAMP.tar.gz" \
/var/www \
/etc/nginx \
/home 2>/dev/null
# --- MariaDB Database Dump ---
mysqldump --all-databases --single-transaction \
-u root > "$BACKUP_DIR/db_$TIMESTAMP.sql" 2>/dev/null
# Compress the SQL dump
gzip "$BACKUP_DIR/db_$TIMESTAMP.sql"
# --- Cleanup: Remove backups older than retention period ---
find "$BACKUP_DIR" -name "*.tar.gz" -mtime +$RETENTION_DAYS -delete
find "$BACKUP_DIR" -name "*.sql.gz" -mtime +$RETENTION_DAYS -delete
echo "Backup completed: $TIMESTAMP"Make it executable:
bash
sudo chmod +x /opt/backups/backup.sh3. Test the Script
bash
sudo /opt/backups/backup.sh
ls -lh /opt/backups/4. Schedule with Cron
Open the root crontab:
bash
sudo crontab -eAdd a line to run the backup every day at 4:00 AM:
bash
0 4 * * * /opt/backups/backup.sh >> /var/log/backup.log 2>&15. Optional: Off-Site Copy with rsync
For true disaster recovery, copy backups to a second server:
bash
rsync -avz /opt/backups/ user@backup-server:/remote/backups/Add this to your cron script after the backup completes.
KVM Linux VPS
Looking for the right Linux VPS?
Put your project into practice right away: Our KVM VPS provide full root access, lightning-fast NVMe storage, and reliable KVM isolation. Flexible prepaid billing with no subscription and personal Discord support.
Full Root Access (SSH)
Datacenter NVMe SSD
4+ Tbps DDoS Protection
100% Prepaid (No Subscription)