How to Automate WordPress Multi-Site Backups with CloudRay

This guide demonstrates how to implement an automated WordPress backup solution for enterprise-grade protection using CloudRay. You will learn how to create isolated backups for WordPress sites (files and database), implement retention policies to manage storage usage, and schedule automated backups using CloudRay’s Schedules feature.

IMPORTANT

Before implementing these backup solutions, ensure you have multiple WordPress sites deployed with isolated users and databases. If you haven’t set this up yet, follow our comprehensive guide on Deploy Multiple WordPress Sites on One Server.

Contents

Adding Servers to CloudRay

Before getting started with your automation, make sure your target servers are connected to CloudRay. If you haven’t done this yet, follow our servers docs to add and manage your server

NOTE

This guide uses Bash scripts, providing a high degree of customisation. You can adapt the scripts to fit your specific Installations needs and environment. Additionally, if you’re using a different version or a different distribution, adjust the commands accordingly.

Create Backup Scripts

To fully protect your WordPress multi-site installation, you can implement two specialised backup solutions. The Backup WordPress Sites Database Script securely exports all database content with transaction consistency, while the Backup WordPress Sites Files Script preserves your complete file structure including themes, plugins, and uploads.

To automate Backups, you will need two bash scripts:

  • Backup WordPress Sites Database Script: This script creates compressed, transaction-safe exports of each WordPress database while verifying data integrity and maintaining proper user isolation
  • Backup WordPress Sites Files Script: This script archives all critical WordPress files while excluding temporary data, with built-in verification to ensure backup reliability

These WordPress backup scripts solve critical challenges for multi-site administrators by providing:

  • Scheduled WordPress backups that run without manual intervention
  • Secure WordPress backups with integrity verification
  • A complete WordPress backup solution covering both database and files

Backup WordPress Sites Database Script

To create your automated database backup script in CloudRay, follow these steps to create the script that will protect your WordPress site critical data:

Screenshot of adding a new database backup script
  1. Go to Scripts → New Script
  2. Name it Backup WordPress Sites Database Script
  3. Add the following script:
#!/bin/bash

# Exit on error
set -e

# Create backup directory if not exists
sudo mkdir -p "{{backup_dir}}" || { echo "Failed to create backup directory"; exit 1; }

{
    echo "=== Starting Database Backup at $(date) ==="
    echo "Host: $(hostname)"
    echo "MySQL Version: $(mysql --version)"

    # Verify MySQL connectivity
    if ! mysql -u "{{db_user1}}" -p"{{db_pass1}}" -e "SHOW DATABASES;" >/dev/null 2>&1; then
        echo "ERROR: Cannot connect to MySQL server"
        exit 1
    fi

    # Backup first WordPress database
    echo "Backing up database {{db1}} to {{backup_dir}}/{{db1}}_db_{{timestamp}}.sql.gz"
    if mysqldump --single-transaction --quick \
        -u "{{db_user1}}" -p"{{db_pass1}}" "{{db1}}" \
        | gzip > "{{backup_dir}}/{{db1}}_db_{{timestamp}}.sql.gz"; then
        
        if gzip -t "{{backup_dir}}/{{db1}}_db_{{timestamp}}.sql.gz"; then
            echo "SUCCESS: {{db1}} backup (Size: $(du -h "{{backup_dir}}/{{db1}}_db_{{timestamp}}.sql.gz" | cut -f1))"
            zgrep -q "wp_options" "{{backup_dir}}/{{db1}}_db_{{timestamp}}.sql.gz" || echo "WARNING: Missing WordPress tables in {{db1}} backup"
        else
            echo "ERROR: Backup verification failed for {{db1}}"
            sudo rm -f "{{backup_dir}}/{{db1}}_db_{{timestamp}}.sql.gz"
        fi
    else
        echo "ERROR: Database backup failed for {{db1}}"
    fi

    # Apply retention policy
    echo "Cleaning up backups older than {{retention_days}} days..."
    find "{{backup_dir}}" -name "*_db_*.sql.gz" -mtime +{{retention_days}} -delete

    echo "=== Database Backup Completed at $(date) ==="
    echo "Remaining backups:"
    ls -lh "{{backup_dir}}"/*_db_*.sql.gz 2>/dev/null || echo "No database backups found"
    echo "Disk usage: $(df -h {{backup_dir}})"
} | tee -a "{{db_log_file}}"

Here is a breakdown of what the Backup WordPress Sites Database Script does:

  • Creates transaction-consistent backups using mysqldump --single-transaction to avoid database locking during backups
  • Compresses database dumps with gzip to minimise storage usage while maintaining data integrity
  • Verifies backup completeness by checking for essential WordPress tables like wp_options
  • Implements automatic retention by deleting backups older than the specified number of days
  • Provides detailed logging with timestamps, success/failure status, and backup sizes
  • Validates MySQL connectivity before attempting backups to prevent partial failures
  • Maintains isolated backups for each WordPress site according to your multi-site architecture
  • Includes corruption checks using gzip -t to automatically detect and remove invalid backups

Backup WordPress Sites Files Script

Similarly, to create your automated WordPress files backup script in CloudRay, follow these steps to create the script:

Screenshot of adding a new file backup script
  1. Go to Scripts → New Script
  2. Name it Backup WordPress Sites Files Script
  3. Add the following script:
#!/bin/bash

# Exit on error
set -e

# Create backup directory if not exists
sudo mkdir -p "{{backup_dir}}" || { echo "Failed to create backup directory"; exit 1; }

{
    echo "=== Starting Backup at $(date) ==="

    for USER in {{user1}}; do
        WP_DIR="/home/$USER/public_html"

        # Verify user directory exists
        if [ ! -d "$WP_DIR" ]; then
            echo "ERROR: Directory $WP_DIR not found for user $USER"
            continue
        fi

        BACKUP_FILE="{{backup_dir}}/${USER}_files_{{timestamp}}.tar.gz"

        echo "Backing up $WP_DIR to $BACKUP_FILE"

        # Create backup with verbose output
        if sudo tar -czvf "$BACKUP_FILE" \
            --exclude='cache/*' \
            --exclude='.git/*' \
            -C / "home/$USER/public_html" 2>&1; then

            # Verify backup integrity
            if sudo gzip -t "$BACKUP_FILE"; then
                echo "SUCCESS: Backup created for $USER (Size: $(du -h "$BACKUP_FILE" | cut -f1))"
            else
                echo "ERROR: Backup verification failed for $USER"
                sudo rm -f "$BACKUP_FILE"
            fi
        else
            echo "ERROR: Backup failed for $USER"
        fi
    done

    echo "=== Backup completed at $(date) ==="
    echo "Disk usage: $(df -h {{backup_dir}})"
} | tee -a "{{log_file}}"

Here is a breakdown of what the Backup WordPress Sites Files Script does:

  • Creates compressed archives of each WordPress site’s public_html directory using tar+gzip for efficient storage
  • Maintains file permissions by running as sudo to properly backup all WordPress files
  • Excludes non-essential files like cache and git directories to reduce backup size
  • Verifies backup integrity with gzip -t to ensure archives are not corrupted
  • Provides detailed logging including timestamps, file sizes, and success/failure status
  • Handles multiple sites by iterating through all configured WordPress users
  • Checks directory existence before attempting backups to prevent errors
  • Tracks disk usage after completion to monitor storage consumption
  • Preserves directory structure using -C flag for proper restoration and outputs verbose progress during archive creation for monitoring

Create a Variable Group

These backup scripts builds on the same variables used in the guide Deploy Multiple WordPress Sites. However, you need to define values for the following placeholders {{backup_dir}}, {{timestamp}}, {{log_file}}, {{db_log_file}}, and {{retention_days}} used in the scrips.

Follow these steps to edit the variable group and include the new variables to ensure that these new values are automatically substituted when the script runs:

Screenshot of adding a new variable group
  1. Navigate to Variable Groups: In your CloudRay project, go to “Scripts” in the top menu and click on “Variable Groups”.
  2. Edit the Variable Group: Click on variable group you created earlier for the WordPress sites and edit it
  3. Add the following variables:
  • backup_dir: The central directory of all backups
  • timestamp: time format for naming the backups
  • log_file: Filesystem backup logs
  • db_log_file: Database backup logs
  • retention_days: Auto-delete backups older than X days

Since the variables are setup, proceed to creating backups schedules with CloudRay.

How to Schedule Automated WordPress Backups for Databases

CloudRay offers Schedules, allowing you to execute scripts automatically at specific intervals or times. This feature is useful for tasks such as automating database backups.

For example, if you want to back up your WordPress sites database on the first day of every month at 12:00 AM, you can configure a CloudRay schedule to handle this automatically.

Here are the steps to achieve this:

  1. Navigate to Schedules: In your CloudRay dashboard, go to the “Schedules” tab.
Screenshot of the location of Schedules in CloudRay's Interface
  1. Click “Add Schedule”: Start creating a new schedule.
Screenshot of the location of Schedules in CloudRay's Interface
  1. Submit Schedule: Click “Submit” to activate your new schedule.
Screenshot of the location of enabled schedule

CloudRay will automatically execute the backup script at the scheduled time, ensuring that your WordPress sites database is regularly backed up without manual intervention.

How to Schedule Automated WordPress Backups for Filesystem

For comprehensive WordPress protection, you can implementing a weekly filesystem backup schedule alongside your database backups.

For example, if you want to backup your WordPress sites filesystem weekly every sunday at 2:00AM, you can configure a CloudRay schedule. Similarly, here is how to achieve this:

  1. Click “Add Schedule”: Start creating a new schedule.
Screenshot of the location of Schedules in CloudRay's Interface
  1. Submit Schedule: Click “Submit” to activate your new schedule.
Screenshot of the location of enabled schedule

With this schedule in place, CloudRay will automatically perform weekly backups of your WordPress files every Sunday at 2:00 AM, ensuring your site content remains protected without manual intervention.

TIP

These scripts are designed for easy reuse across multiple WordPress sites. Simply edit the variable group to include additional database credentials (db2, db_user2, etc.) or users (user2, user3) as needed. CloudRay will automatically apply the updated variables when the scheduled backups execute, allowing the same scripts to manage backups for any number of WordPress installations.