How to Set Up Automatic Backups for WordPress on a VPS

How to Set Up Automatic Backups for WordPress on a VPS

1. The Strategy: Off-Site or Bust

Never store backups on the same physical disk as your live site. If the server’s storage fails or the VPS is corrupted, your backups die with the site.

  • The Destination: Use S3-compatible storage (Backblaze B2, AWS S3, or Wasabi) for cost-effective, durable storage.
  • The Tool: Rclone. It is the “Swiss Army Knife” of cloud storage sync, supporting over 40 cloud providers and offering encrypted transfers.

2. Creating the Backup Script

Instead of a heavy plugin, use a simple Bash script. This script should perform three core actions:

  1. Dump the Database: Use mysqldump to create a .sql file.
  2. Compress Files: Create a tar.gz archive of your wp-content and wp-config.php.
  3. Sync to Cloud: Use Rclone to push these to your remote bucket.

Example Script Logic:

Bash

# Dump DB
mysqldump -u [user] -p[pass] [db_name] > /tmp/db_backup.sql

# Archive Files
tar -czf /tmp/site_files.tar.gz /var/www/html

# Sync with Rclone
rclone copy /tmp/site_files.tar.gz remote:my-bucket/backups/

3. Automating with System Cron

Once your script is tested and running, you need to automate it using the system’s crontab.

  • The Schedule: For most sites, a daily backup at 2:00 AM (server time) is the sweet spot.
  • The Command: crontab -e
  • The Entry: 0 2 * * * /usr/local/bin/backup-script.sh > /dev/null 2>&1

4. Implementing Log Rotation & Retention

Your cloud bucket shouldn’t grow indefinitely. You need a retention policy so you don’t pay for backups from three years ago.

  • Lifecycle Rules: Configure your S3 bucket (via the provider’s dashboard) to automatically delete files older than 30 days.
  • Local Cleanup: Ensure your script deletes the temporary files in /tmp/ after a successful upload to prevent the local disk from filling up.

5. Verification: The “Restoration Drill”

A backup is only a success if it can be restored.

  • Automated Testing: Set up a staging environment or a local Docker container and try to restore the site using your automated backup once a month.
  • Checksums: Use Rclone’s --checksum flag to ensure the data integrity of the files during the transfer process.

Leave a Reply

Your email address will not be published. Required fields are marked *