β»οΈAutomatic database backup (Updated)
// Complete db backup script for S3 bucket of aws
// make sure to create seperate credential file
// DIR path /var/backups/
#######################################################################################
#!/bin/bash
# Load credentials from an external file
# Load all variables from an external file
source /var/backups/"your_credentials.sh"
timestamp=$(date +"%F-%H%M")
filename="$backup_path/${db_name}_backup_$timestamp.sql.gz"
# Ensure backup directory exists
mkdir -p $backup_path
# Take a database backup and compress it
mysqldump -u$db_user -p$db_password $db_name | gzip > $filename
# Check if the backup was created successfully
if [ $? -ne 0 ]; then
# Log process and notify via email if backup fails
{
echo "Subject: Database Backup Failed"
echo "To: $email"
echo "From: [email protected]"
echo ""
echo "Database backup failed for $db_name at $timestamp."
} | /usr/sbin/sendmail -t
exit 1
fi
# Upload the backup to AWS S3
aws s3 cp $filename s3://$s3_bucket/database-backups/ --region eu-central-1
# Retain only the latest 2 backups in S3
backup_files=$(aws s3 ls s3://$s3_bucket/database-backups/ --region eu-central-1 | sort | awk '{print $4}')
backup_count=$(echo "$backup_files" | wc -l)
if [ $backup_count -gt 2 ]; then
files_to_delete=$(echo "$backup_files" | head -n $(($backup_count - 2)))
for file in $files_to_delete; do
aws s3 rm s3://$s3_bucket/database-backups/$file --region eu-central-1
done
fi
# Check if the upload was successful
if [ $? -eq 0 ]; then
# Retain only the latest 2 local backups
local_backup_files=$(ls -1 $backup_path | sort)
local_backup_count=$(echo "$local_backup_files" | wc -l)
if [ $local_backup_count -gt 2 ]; then
local_files_to_delete=$(echo "$local_backup_files" | head -n $(($local_backup_count - 2)))
for file in $local_files_to_delete; do
rm $backup_path/$file
done
fi
# Remove local backup file after successful upload
rm $filename
# Log process and notify via email of success optional and not tested yet
{
echo "Subject: Database Backup Completed Successfully"
echo "To: $email"
echo "From: [email protected]"
echo ""
echo "Database backup completed successfully: $filename"
} | /usr/sbin/sendmail -t
else
# Log process and notify via email if upload fails
{
echo "Subject: Database Backup Upload Failed"
echo "To: $email"
echo "From: [email protected]"
echo ""
echo "Database backup upload failed for $filename at $timestamp."
} | /usr/sbin/sendmail -t
exit 1
fiCreate a database backup script which takes backup of the database, compresses it, and stores with name, time, date month year.
PreviousCLI schedule task and consume serviceNextExecute a command from host to docker using terminal
Last updated