Set Up Automatic MySQL Backups on Linux With a Cron Job
Data backup is a critical task for any website or application. Automating this process saves you time and ensures you never forget to back up.
Let the system do the work for you.
This guide will show you how to create a simple shell script to back up a MySQL database, and then use `cron` to schedule this script to run daily.
Step 1: Create the Backup Script
First, let's create a script file. Open the terminal and type:
Paste the following content into the file, and replace the `DB_USER`, `DB_PASS`, `DB_NAME`, and `BACKUP_DIR` values with your information:
Save the file (Ctrl+X, Y, Enter). Then, make the file executable:
Step 2: Schedule with a Cron Job
Cron is a utility on Linux that allows you to run tasks on a predefined schedule.
Open the crontab editor:
Add the following line to the end of the file to schedule the script to run at 2 AM every day:
Save the file and exit. Now, your system will automatically create a compressed backup of your database every day. You should combine this solution with syncing the backup files to a cloud storage service for added safety.
Also available in Vietnamese
Read Vietnamese version →