Backup MySQL Databases on Linux Server with Cron
263

There are several ways to automate backups of MySQL databases on a Linux server using cron. Here is one way you could do it:

  1. First, create a shell script that performs the backup. This script should use the mysqldump command to create a MySQL dump file, which contains the SQL commands needed to recreate the database.

Here is an example script that performs a backup of a database named "mydb" and saves the dump file to a directory named "backups":

#!/bin/bash 
# set up some variables 

DATE=$(date +"%Y-%m-%d") 
BACKUP_DIR="/path/to/backups" 
MYSQL_USER="mysql_username" 
MYSQL_PASSWORD="mysql_password" 
DATABASE_NAME="mydb" 
# create the backup directory if it doesn't exist mkdir -p "$BACKUP_DIR" # create the dump file mysqldump --user=$MYSQL_USER --password=$MYSQL_PASSWORD $DATABASE_NAME > "$BACKUP_DIR/$DATABASE_NAME-$DATE.sql"

 

  1. Make the script executable by running the following command:

chmod +x /path/to/mysql_backup.sh

  1. Open the crontab file for the user that will run the script:

Copy code

crontab -e

  1. Add a line to the crontab file to run the script at the desired frequency. For example, to run the script every day at 3:00 AM, you would add the following line:

Copy code

0 3 * * * /path/to/mysql_backup.sh

  1. Save the crontab file and exit.

The script should now run at the specified time and create a MySQL dump file in the "backups" directory. You can customize the script and the crontab entry to meet your specific needs. For example, you could compress the dump file to save space, or you could copy the dump file to a remote location for safekeeping.

If you are looking for consultation, fill the Contact Form below.
Our virtues and our failings are inseparable, like force and matter. When they separate, man is no more. Nikola Tesla
Haluk YAMANER - Personal
Contact Form
You must complete Security Verification to submit your form.