BASH

Automating Website Backup to Remote Server

Learn to create a robust Bash script for backing up website files and databases, then securely transfer them to a remote server using tar and rsync.

#!/bin/bash
# Configuration
SOURCE_DIR="/var/www/html"
BACKUP_DIR="/tmp/website_backup"
REMOTE_USER="user"
REMOTE_HOST="your.backup.server.com"
REMOTE_PATH="/backups/website"
DB_NAME="your_database_name"
DB_USER="db_user"
DB_PASS="db_password"

TIMESTAMP=$(date +"%Y%m%d%H%M%S")
BACKUP_FILE="${BACKUP_DIR}/website_backup_${TIMESTAMP}.tar.gz"
DB_BACKUP_FILE="${BACKUP_DIR}/db_backup_${TIMESTAMP}.sql"

# Create backup directory if it doesn't exist
mkdir -p "${BACKUP_DIR}"

# Backup Database
mysqldump -u"${DB_USER}" -p"${DB_PASS}" "${DB_NAME}" > "${DB_BACKUP_FILE}" || { echo "Database backup failed!"; exit 1; }

# Archive website files and database backup
tar -czvf "${BACKUP_FILE}" -C "$(dirname "${SOURCE_DIR}")" "$(basename "${SOURCE_DIR}")" "${DB_BACKUP_FILE}" || { echo "Archiving failed!"; exit 1; }

# Transfer backup to remote server
rsync -avz "${BACKUP_FILE}" "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_PATH}" || { echo "Remote transfer failed!"; exit 1; }

# Clean up local backup files
rm -f "${BACKUP_FILE}" "${DB_BACKUP_FILE}"

echo "Backup completed successfully to ${REMOTE_HOST}:${REMOTE_PATH}"
How it works: This script automates a full website backup process. It first backs up a MySQL database using `mysqldump`, then archives specified website files along with the database dump into a single `.tar.gz` file. Finally, it securely transfers this archive to a remote server using `rsync` over SSH, and cleans up local temporary files, making it a robust solution for regular backups.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs