LightYear
/Docs
DocsStorageAutomate MySQL Backups to Object Storage

Automate MySQL Backups to Object Storage

Schedule automated MySQL database backups and upload them to object storage using a cron job.

intermediate
8 min read
LightYear Team
Updated April 24, 2026
mysqlbackupobject-storagecronautomation

Overview

This guide sets up a cron job that dumps your MySQL database and uploads it to LightYear Object Storage daily.

Prerequisites

  • MySQL server running on your server
  • Object storage bucket created
  • AWS CLI configured with your object storage credentials

Step 1 — Create the Backup Script

>_BASH
$cat > /usr/local/bin/mysql-backup.sh << 'EOF'
$#!/bin/bash
$set -e
$
$# Configuration
$DB_NAME="myapp"
$DB_USER="root"
$DB_PASS="your-password"
$BUCKET="my-backups"
$ENDPOINT="https://storage.lightyear.host"
$RETENTION_DAYS=30
$
$# Create backup
$TIMESTAMP=$(date +%Y%m%d_%H%M%S)
$BACKUP_FILE="/tmp/backup_${DB_NAME}_${TIMESTAMP}.sql.gz"
$
$mysqldump -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" | gzip > "$BACKUP_FILE"
$
$# Upload to object storage
$aws s3 cp "$BACKUP_FILE" "s3://$BUCKET/mysql/$DB_NAME/" --endpoint-url "$ENDPOINT"
$
$# Clean up local file
$rm "$BACKUP_FILE"
$
$# Delete old backups
$aws s3 ls "s3://$BUCKET/mysql/$DB_NAME/" --endpoint-url "$ENDPOINT" | awk '{print $4}' | while read -r file; do
$ file_date=$(echo "$file" | grep -oP '\d{8}')
$ if [[ $(date -d "$file_date" +%s) -lt $(date -d "-$RETENTION_DAYS days" +%s) ]]; then
$ aws s3 rm "s3://$BUCKET/mysql/$DB_NAME/$file" --endpoint-url "$ENDPOINT"
$ fi
$ done
$
$echo "Backup complete: $BACKUP_FILE"
$EOF
$chmod +x /usr/local/bin/mysql-backup.sh

Step 2 — Test the Script

>_BASH
$/usr/local/bin/mysql-backup.sh

Step 3 — Schedule with Cron

>_BASH
$crontab -e

Add:

# Run MySQL backup daily at 2:00 AM 0 2 * * * /usr/local/bin/mysql-backup.sh >> /var/log/mysql-backup.log 2>&1

Step 4 — Verify Backups

>_BASH
$aws s3 ls s3://my-backups/mysql/myapp/ --endpoint-url https://storage.lightyear.host

Restoring from Backup

>_BASH
$# Download the backup
$aws s3 cp s3://my-backups/mysql/myapp/backup_myapp_20250115_020000.sql.gz . --endpoint-url https://storage.lightyear.host
$
$# Restore
$gunzip -c backup_myapp_20250115_020000.sql.gz | mysql -u root -p myapp

Was this article helpful?

Your cookie choices for this website

This site uses cookies and related technologies, as described in our privacy policy, for purposes that may include site operation, analytics, and enhanced user experience. You may choose to consent to our use of these technologies, or manage your own preferences. Cookie policy