0
0
MysqlHow-ToBeginner · 4 min read

How to Schedule Automatic Backup in MySQL Easily

To schedule automatic backups in MySQL, use the mysqldump command to export your database and set up a system scheduler like cron on Linux to run this command regularly. This combination automates backups by running the dump command at specified times without manual intervention.
📐

Syntax

The basic syntax to back up a MySQL database using mysqldump is:

  • mysqldump -u [username] -p[password] [database_name] > [backup_file.sql]
  • cron syntax to schedule jobs follows: minute hour day month weekday command

This means you specify when the backup runs and what command to execute.

bash
mysqldump -u username -ppassword database_name > backup.sql

# Cron job format example:
# 0 2 * * * /path/to/backup_script.sh
💻

Example

This example shows how to create a shell script to back up a MySQL database and schedule it to run daily at 2 AM using cron.

bash
# backup_script.sh
#!/bin/bash

# Variables
USER="root"
PASSWORD="your_password"
DATABASE="mydatabase"
BACKUP_DIR="/home/user/mysql_backups"
DATE=$(date +"%Y-%m-%d_%H-%M-%S")

# Create backup directory if not exists
mkdir -p "$BACKUP_DIR"

# Run mysqldump
mysqldump -u "$USER" -p"$PASSWORD" "$DATABASE" > "$BACKUP_DIR/${DATABASE}_backup_$DATE.sql"

# Cron job entry (run 'crontab -e' to add):
# 0 2 * * * /bin/bash /home/user/backup_script.sh
⚠️

Common Pitfalls

Common mistakes when scheduling MySQL backups include:

  • Putting a space between -p and the password in mysqldump (it should be -ppassword, no space).
  • Not giving execute permission to the backup script (chmod +x backup_script.sh).
  • Not specifying full paths in cron jobs, causing commands to fail.
  • Storing passwords in plain text scripts without proper security.
bash
# Wrong way (space after -p):
mysqldump -u root -p password mydatabase > backup.sql

# Right way (no space):
mysqldump -u root -ppassword mydatabase > backup.sql
📊

Quick Reference

Command/ConceptDescription
mysqldump -u user -ppassword db > file.sqlExport MySQL database to a file
crontab -eEdit cron jobs for scheduling tasks
0 2 * * * /path/to/script.shRun script daily at 2 AM
chmod +x script.shMake script executable
mkdir -p /path/to/dirCreate directory if it doesn't exist

Key Takeaways

Use mysqldump to export your MySQL database for backup.
Schedule backups automatically with cron jobs on Linux systems.
Avoid spaces between -p and password in mysqldump commands.
Always use full paths and set execute permissions for backup scripts.
Secure your backup scripts and passwords to protect your data.