2 minutes
Shell Script Backup Wordpress
This tutorial will guide you through the process of backing up your WordPress data and database to a remote location using rsync and Amazon S3. The backup will be scheduled to run every week at midnight on Saturday, and it will keep a maximum of 10 backups. Additionally, an email notification will be sent once the backup is completed.
Prerequisites
- Docker and Docker Compose installed
- AWS CLI configured with access to your S3 bucket
rsyncandmailutilities installed- A running WordPress instance with Docker Compose
Step 1: Create the Backup Script
Create a bash script named backup-script.sh with the following content:
#!/bin/bash
# Configuration
BACKUP_DIR="/path/to/backup"
REMOTE_DIR="user@remote:/path/to/remote/backup"
S3_BUCKET="s3://your-bucket-name"
WORDPRESS_DIR="/path/to/wordpress/html"
DB_CONTAINER="wordpress_db"
DB_NAME="wordpress"
DB_USER="wordpress"
DB_PASSWORD="wordpress"
EMAIL="your-email@example.com"
MAX_BACKUPS=10
# Create backup directory if it doesn't exist
mkdir -p $BACKUP_DIR
# Get current date
DATE=$(date +"%Y-%m-%d")
# Backup WordPress files
tar -czf $BACKUP_DIR/wordpress-files-$DATE.tar.gz -C $WORDPRESS_DIR .
# Backup database
docker exec $DB_CONTAINER /usr/bin/mysqldump -u $DB_USER --password=$DB_PASSWORD $DB_NAME > $BACKUP_DIR/wordpress-db-$DATE.sql
# Sync to remote location using rsync
rsync -avz $BACKUP_DIR/wordpress-files-$DATE.tar.gz $REMOTE_DIR
rsync -avz $BACKUP_DIR/wordpress-db-$DATE.sql $REMOTE_DIR
# Sync to Amazon S3
aws s3 cp $BACKUP_DIR/wordpress-files-$DATE.tar.gz $S3_BUCKET
aws s3 cp $BACKUP_DIR/wordpress-db-$DATE.sql $S3_BUCKET
# Remove old backups
cd $BACKUP_DIR
ls -t | grep 'wordpress-files\|wordpress-db' | sed -e "1,${MAX_BACKUPS}d" | xargs -d '\n' rm -f
# Send email notification
echo "Backup completed successfully on $DATE" | mail -s "WordPress Backup Notification" $EMAIL
Replace the placeholder paths and values with your actual configuration.
Step 2: Make the Script Executable
Make the script executable by running the following command:
chmod +x /path/to/your/backup-script.sh
Step 3: Schedule the Script with Cron
To schedule the script to run every week at midnight on Saturday, set up a cron job:
Open the crontab file:
crontab -e
Add the following line to schedule the script:
0 0 * * 6 /path/to/your/backup-script.sh
This cron job will run the script at midnight every Saturday.
Conclusion
By following this tutorial, you have set up a backup system for your WordPress data and database. The backups will be stored both on a remote server and in an Amazon S3 bucket, with a maximum of 10 backups retained. Additionally, you will receive an email notification once the backup is completed.