Automate daily compressed SQL dumps with automated timestamping, 30-day retention cleanup, and cron scheduling
By following this guide, your MySQL or MariaDB databases will back up automatically every night into compressed .sql.gz archives. A retention script will automatically delete archives older than 30 days to conserve disk space.
Spin up an Ubuntu 24.04 instance with instant activation to test this tutorial:
Deploy IndSoft VPSA Linux VPS running MySQL or MariaDB with at least 5 GB free disk space.
Create a restricted directory and generate a dedicated database user with SELECT and LOCK TABLES privileges.
sudo mkdir -p /var/backups/mysql
sudo chmod 700 /var/backups/mysql
sudo mysql -e "CREATE USER 'backupuser'@'localhost' IDENTIFIED BY 'STRONG_BACKUP_PASSWORD'; GRANT SELECT, SHOW VIEW, RELOAD, REPLICATION CLIENT, EVENT, TRIGGER, LOCK TABLES ON *.* TO 'backupuser'@'localhost'; FLUSH PRIVILEGES;"Create a script at /usr/local/bin/mysql-backup.sh to dump all databases with gzip compression.
sudo nano /usr/local/bin/mysql-backup.sh
# Script sets: BACKUP_DIR, DATE=$(date +%Y-%m-%d_%H%M%S)
# mysqldump --all-databases | gzip > $BACKUP_DIR/db-$DATE.sql.gz
# find $BACKUP_DIR -name "*.sql.gz" -mtime +30 -delete
sudo chmod +x /usr/local/bin/mysql-backup.shAdd a crontab entry to execute the backup script automatically every night at 2:30 AM.
sudo crontab -e
# Add: 30 2 * * * /usr/local/bin/mysql-backup.sh > /var/log/mysql-backup.log 2>&1Run this quick verification check to confirm your installation is responding properly:
sudo /usr/local/bin/mysql-backup.sh && ls -lh /var/backups/mysqlQuick resolutions for frequent setup pitfalls and configuration issues.
/root/.my.cnf configuration file with permissions chmod 600 so scripts don't expose passwords in process lists.
gunzip < backup.sql.gz | mysql staging_db.