ป้ายกำกับ: Cron Job

Linux Auto Backup MySQL/MariaDB: Step-by-Step GuideLinux Auto Backup MySQL/MariaDB: Step-by-Step Guide

Data is the most critical component of any server, as it cannot be recovered if lost due to unforeseen events such as server crashes, incorrect commands, or hacking attempts. Regular backups are essential to prevent data loss. This article will guide you on creating an automated backup script for MySQL or MariaDB databases on a Linux server.

Creating the Backup Script

To create the backup script, use the following command:

SQL

sudo nano /usr/local/sbin/backup_mysql.sh

The script should be placed in /usr/local/sbin because this directory is for root scripts that regular users cannot execute.

SQL

#!/bin/bash

# --- Set Variables ---
DB_USER="<username>"
DB_PASS="<password>"
DATE=$(date +%Y%m%d)
BACKUP_DIR="/var/backups/mysql/$DATE"

# --- Check and Create Backup Directory ---
if [ ! -d "$BACKUP_DIR" ]; then
    mkdir -p "$BACKUP_DIR"
    echo "Creating directory: $BACKUP_DIR"
fi

# --- Start Database Backup Process ---
echo "--- Starting Database Backup ---"

DATABASES=$(mysql -u$DB_USER -p$DB_PASS -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema|performance_schema|mysql|sys)")

for DB in $DATABASES; do
    echo "  > Backing up database: $DB"
    mysqldump --user=$DB_USER --password=$DB_PASS --single-transaction --events --routines --triggers --add-drop-database "$DB" | gzip > "$BACKUP_DIR/$DB.sql.gz"

    if [ $? -eq 0 ]; then
        echo "    - Success: $BACKUP_DIR/$DB.sql.gz"
    else
        echo "    - Error backing up database: $DB"
    fi
done

echo "--- Database Backup Complete ---"

# --- Backup Users and Permissions ---
echo "--- Starting User and Permissions Backup ---"

mysqldump -u$DB_USER -p$DB_PASS --single-transaction --skip-triggers --compact mysql user db tables_priv columns_priv procs_priv > "$BACKUP_DIR/users_and_grants.sql"
if [ $? -eq 0 ]; then
    echo "    - Success: $BACKUP_DIR/users_and_grants.sql"
else
    echo "    - Error backing up user accounts and grants"
fi

echo "--- User and Permissions Backup Complete ---"

Setting Up the Cron Job

To automate the backup process, set up a cron job. Edit the crontab file using:

SQL

sudo crontab -e

Add the following line to schedule the backup script to run daily at 2 AM:

SQL

0 2 * * * /usr/local/sbin/backup_mysql.sh

Conclusion

Automating the backup process for MySQL or MariaDB databases on a Linux server is crucial for data protection. By following the steps outlined in this article, you can create a reliable backup script and schedule it to run automatically. This ensures that your data is regularly backed up, reducing the risk of data loss due to unforeseen events.