A shell script is a collection of commands to perform a specific job. MySQL is a relational database management system widely used on Linux systems. Amazon S3 is a cloud storage device provided by Amazon Web Services. It’s a good practice for the system administrator to back up databases at regular intervals and store them in a remote location like Amazon S3.
This tutorial contains a shell script that creates MySQL databases backup and uploads them to Amazon S3 buckets. You can also use this shell script to back up MariaDB or Amazon Aurora (MySQL compatible) databases.
Backup MySQL Databases to S3
Use the below step-by-step tutorial to back up the MySQL databases and upload them to the Amazon S3 bucket.
1. Install AWS CLI
In order to use this script, the system must have AWS CLI installed.
2. Create S3 Bucket
Login to AWS Management Console and create a new s3 bucket.
Alternatively, you can also create s3 bucket via AWS CLI. The command will be like:
aws s3api create-bucket --bucket s3-bucket-name --region us-east-1
Just replace the bucket name and region.
3. Shell Script to Backup MySQL database to S3
Copy the below shell script to a file like db-backup.sh. This script uses mysqldump command to create databases backups. Then use gzip command to archive backup files and finally use aws command to upload backup files to Amazon S3 bucket.
Create a file like /backup/scripts/s3-backup-mysql.sh in edit your favorite text editor. Then add the below content:
Update all the necessary variables as per your system environment.
4. How to run backup script
Set the execute (x) permission on script:
chmod +x s3-backup-mysql.sh
Then run the backup script.
5. Schedule backup script to run daily
Schedule the shell script using crontab to run on a daily basis.
Add the below settings to end of the file:
# Run daily @ 2am 0 2 * * * /backup/scripts/s3-backup-mysql.sh > /dev/null 2>&1
Save the file and close it.
This tutorial provides you with a shell script to back up MySQL databases and upload them to the Amazon S3 bucket. That could be helpful for you to automate database backups and save a copy on cloud storage.