
Database backups are essential for protecting application data against accidental deletion, server failures, database corruption, and unexpected outages. However, manually creating backups is unreliable, especially when managing production applications.
A better approach is to automate the entire process using Bash scripts, Cron jobs, and Amazon S3.
In this guide, you'll learn how to create database backups automatically, compress them, upload them to AWS S3, schedule daily backups, and clean up old local backup files.
We'll use MySQL for the primary example and cover MongoDB commands at the end.
What You'll Build
By the end of this tutorial, you'll have an automated backup workflow that:
Creates a database backup using a Bash script.
Compresses the backup to reduce storage requirements.
Uploads the backup to an Amazon S3 bucket.
Runs automatically at a scheduled time using Cron.
Logs backup results for troubleshooting.
Removes old local backup files according to a retention policy.
1. Understand the Architecture
The backup process follows a simple workflow:
Cron triggers the backup script at the scheduled time.
Bash executes the database backup command.
The generated SQL file is compressed.
The AWS CLI uploads the compressed file to S3.
The script records the result in a log file.
Old local backups are removed according to the configured retention period.
For example, a production Node.js application might use a MySQL database hosted on a VPS. The VPS creates a daily backup and uploads it to a private S3 bucket.
This keeps a copy of your database outside the application server, helping protect against local disk failures and server loss.
2. Prerequisites
Before starting, make sure you have:
A Linux server or VPS.
A running MySQL database.
An AWS account.
An Amazon S3 bucket.
AWS CLI installed and configured.
Bash and Cron available on your server.
Check whether the required commands are available:
bash --version
mysql --version
mysqldump --version
aws --version
crontab -lInstall missing packages on Ubuntu or Debian:
sudo apt update
sudo apt install mysql-client awscli cron -yStart and enable the Cron service:
sudo systemctl enable --now cronOn distributions using a different service name, such as some RHEL-based systems, the service may be called crond.
3. Create an AWS S3 Bucket
Open the AWS Management Console and navigate to Amazon S3.
Create a bucket, for example:
devbyte-database-backupsChoose an AWS Region appropriate for your application and data residency requirements.
For database backups, configure the following security settings:
Keep Block Public Access enabled.
Disable public access to backup objects.
Enable server-side encryption.
Consider enabling S3 Versioning for additional recovery options.
Configure an S3 Lifecycle rule to transition or expire old backups when appropriate.
Avoid storing database backups in a publicly accessible bucket. These files may contain customer information, passwords, email addresses, or other sensitive data.
Verify the Bucket
After configuring AWS credentials, check whether the bucket is accessible:
aws s3 ls s3://devbyte-database-backups/Replace the example bucket name with your actual bucket name.
If the command succeeds, your AWS CLI configuration can access the bucket. If it fails, verify your credentials, AWS Region, bucket name, and IAM permissions.
4. Configure AWS Credentials Securely
The AWS CLI needs permission to upload files to S3.
For a VPS running on AWS, prefer an attached IAM role with only the permissions required for the backup process.
For a server hosted elsewhere, use a dedicated IAM identity with narrowly scoped permissions. Protect its credentials and rotate them according to your security policy.
Avoid placing access keys directly inside a Bash script.
For example, if you are using an AWS CLI profile named database-backup, test it with:
aws sts get-caller-identity --profile database-backupThen verify access to the target bucket:
aws s3 ls s3://devbyte-database-backups/ \
--profile database-backupThe IAM permissions should be restricted to the required S3 bucket and operations. Depending on your configuration, multipart uploads and cleanup operations may require additional permissions.
Security note: If possible, use IAM roles instead of long-lived access keys. Never commit AWS credentials to GitHub or include them in public repositories.
5. Configure MySQL Backup Credentials
The backup script needs permission to read the database.
Avoid putting the database password directly in the script or passing it through command-line arguments.
One option is a MySQL client option file.
Create a dedicated configuration file:
sudo nano /etc/mysql/backup-client.cnfAdd the following configuration:
[client]
user=backup_user
password=YOUR_STRONG_DATABASE_PASSWORD
host=127.0.0.1
port=3306Replace the username, password, and host with your actual database settings.
Restrict access to the file:
sudo chown root:root /etc/mysql/backup-client.cnf
sudo chmod 600 /etc/mysql/backup-client.cnfBecause this file is owned by root, run the backup script through root's Cron or another appropriately configured service account that can read it.
Create a dedicated MySQL user with only the permissions needed for the backup method you choose. Depending on the MySQL version and database features, mysqldump may require additional privileges for routines, events, triggers, tablespaces, or transaction-related options.
For production environments, verify the permissions against your database version and backup requirements.
6. Create the Bash Backup Script
Now create a directory for the backup script:
sudo mkdir -p /opt/db-backup
sudo nano /opt/db-backup/mysql-backup.shAdd the following script:
#!/usr/bin/env bash
set -Eeuo pipefail
umask 077
# Database configuration
DB_NAME="my_application"
MYSQL_CNF="/etc/mysql/backup-client.cnf"
# Backup configuration
BACKUP_DIR="/var/backups/mysql"
S3_BUCKET="s3://devbyte-database-backups"
S3_PREFIX="mysql"
LOG_FILE="/var/log/mysql-backup.log"
# Retain local backups for 7 days
RETENTION_DAYS=7
# Use a UTC timestamp for predictable backup naming
TIMESTAMP="$(date -u +'%Y-%m-%d_%H-%M-%S')"
HOSTNAME_SAFE="$(hostname -s | tr -cd '[:alnum:]_.-')"
BACKUP_FILE="${BACKUP_DIR}/${DB_NAME}_${TIMESTAMP}.sql.gz"
S3_KEY="${S3_BUCKET}/${S3_PREFIX}/${HOSTNAME_SAFE}/${DB_NAME}_${TIMESTAMP}.sql.gz"
# Ensure the backup directory exists
mkdir -p "$BACKUP_DIR"
# Redirect output to the log
exec >> "$LOG_FILE" 2>&1
echo "[$(date -u +'%Y-%m-%dT%H:%M:%SZ')] Backup started"
# Ensure temporary or incomplete backup files are removed on failure
cleanup() {
local exit_code=$?
if [[ "$exit_code" -ne 0 ]]; then
rm -f -- "$BACKUP_FILE"
echo "[$(date -u +'%Y-%m-%dT%H:%M:%SZ')] Backup failed with exit code $exit_code"
fi
}
trap cleanup EXIT
# Verify that the required tools are available
command -v mysqldump >/dev/null 2>&1
command -v gzip >/dev/null 2>&1
command -v aws >/dev/null 2>&1
# Verify the database configuration exists
test -r "$MYSQL_CNF"
# Create and compress the database backup
mysqldump \
--defaults-extra-file="$MYSQL_CNF" \
--single-transaction \
--quick \
--routines \
--events \
--triggers \
"$DB_NAME" | gzip -c > "$BACKUP_FILE"
# Validate the compressed file
gzip -t "$BACKUP_FILE"
test -s "$BACKUP_FILE"
# Upload the backup to S3
aws s3 cp "$BACKUP_FILE" "$S3_KEY" \
--only-show-errors \
--sse AES256
# Delete old local backups only after the upload succeeds
find "$BACKUP_DIR" \
-maxdepth 1 \
-type f \
-name "${DB_NAME}_*.sql.gz" \
-mtime "+${RETENTION_DAYS}" \
-delete
echo "[$(date -u +'%Y-%m-%dT%H:%M:%SZ')] Backup uploaded successfully: $S3_KEY"Important Configuration Details
Update these variables before running the script:
DB_NAME="my_application"
MYSQL_CNF="/etc/mysql/backup-client.cnf"
BACKUP_DIR="/var/backups/mysql"
S3_BUCKET="s3://devbyte-database-backups"
RETENTION_DAYS=7The script uses --single-transaction, which is useful for consistent backups of transactional tables such as InnoDB tables. It does not guarantee a consistent snapshot of nontransactional tables, and database changes involving schema operations may require additional care.
The gzip -t command checks the compressed file's integrity before uploading it.
The script removes old local backups only after the upload succeeds. However, a successful upload does not prove that the backup can be restored. Restore testing is covered later in this guide.
The --sse AES256 option requests S3 server-side encryption with Amazon S3-managed keys. If your organization requires AWS KMS encryption, configure the appropriate KMS key and permissions instead.
Make the Script Executable
Run:
sudo chmod 750 /opt/db-backup/mysql-backup.shBecause the script uses a root-owned MySQL configuration file, test it as root:
sudo /opt/db-backup/mysql-backup.shReview the log:
sudo tail -n 50 /var/log/mysql-backup.logIf the upload succeeds, verify that the object exists:
aws s3 ls s3://devbyte-database-backups/mysql/You can also list the objects under a particular database prefix.
7. Schedule Automated Backups Using Cron
Cron allows Linux systems to execute commands automatically at specified times.
Open the root user's Cron configuration:
sudo crontab -eAdd this entry to run the backup every day at 2:00 AM server time:
0 2 * * * /opt/db-backup/mysql-backup.shSave the file.
Understand the Cron Expression
0 2 * * *
│ │ │ │ │
│ │ │ │ └── Day of the week
│ │ │ └──── Month
│ │ └────── Day of the month
│ └──────── Hour
└────────── MinuteThis expression means:
Minute:
0Hour:
2Day of month: every day
Month: every month
Day of week: every day
Important: Cron uses the server's configured timezone unless you explicitly configure otherwise. Check it with:
timedatectlIf your server uses UTC, the job runs at 2:00 AM UTC, not necessarily 2:00 AM Indian Standard Time.
To schedule the job at 2:00 AM IST, configure the server's timezone appropriately or use a supported Cron timezone setting.
Verify the Cron Job
List root's scheduled jobs:
sudo crontab -lCheck Cron service status:
sudo systemctl status cronOn systems using crond, check that service instead.
Cron jobs run in a limited environment, so scripts should use absolute paths and must not depend on shell profiles or interactive terminal settings.
8. Verify That Backups Reach S3
After the scheduled job runs, verify that backup objects exist in the expected S3 prefix.
aws s3 ls s3://devbyte-database-backups/mysql/ \
--recursiveTo check a particular backup file, use:
aws s3api head-object \
--bucket devbyte-database-backups \
--key mysql/YOUR_HOSTNAME/my_application_YOUR_TIMESTAMP.sql.gzReplace the key with the actual object key created by the script.
This confirms that S3 can return metadata for the object. It does not validate the contents or prove that the database can be restored.
For better monitoring, consider sending alerts when the script fails or when a scheduled backup has not arrived within an expected window.
A production setup should distinguish between:
Backup command success.
Upload success.
Backup freshness.
Restore success.
These are separate checks.
9. Configure S3 Lifecycle Rules
Local retention keeps your VPS disk from filling up, but it does not control the long-term cost of storing backup objects in S3.
Use S3 Lifecycle rules to manage older backups.
For example, your retention policy might be:
Keep daily backups for 30 days.
Transition older backups to a lower-cost storage class where appropriate.
Expire backups after a defined recovery window.
Keep monthly backups longer if business requirements demand it.
These are example values, not universal recommendations. Set retention based on your recovery requirements, compliance obligations, and storage budget.
Before configuring expiration, confirm that the policy will not delete backups you may still need. If S3 Versioning is enabled, understand how lifecycle rules affect current and noncurrent object versions.
10. Add More Production Safeguards
The basic script is a useful starting point, but production backups require additional protections.
Prevent Overlapping Runs
If a backup takes longer than expected, a later Cron execution could start another backup. Use flock to prevent overlapping executions.
For example, change the Cron entry to:
0 2 * * * /usr/bin/flock -n /var/lock/mysql-backup.lock /opt/db-backup/mysql-backup.shVerify the flock path on your system.
If a previous backup is still running, the new invocation will exit without starting another backup.
Monitor Backup Freshness
A script can exit successfully on one day and fail the next. Monitoring should detect missing or stale backups rather than only checking whether a script ran.
Useful checks include:
Alert if no backup appears within the expected time window.
Record the backup timestamp and size.
Alert on repeated upload failures.
Monitor server disk usage.
Test restoration periodically.
Protect Backups Against Deletion
Consider enabling S3 Versioning and, when justified by your recovery and security requirements, S3 Object Lock.
Object Lock can protect supported objects from deletion or modification during a configured retention period. It must be planned and configured correctly; it is not a substitute for access control or restore testing.
Encrypt Sensitive Data
S3 server-side encryption protects objects at rest within S3, but you may also want client-side encryption before upload for sensitive databases.
If you encrypt the backup before uploading, securely manage the encryption keys. Losing the keys may make every backup unrecoverable.
Never store encryption keys beside the encrypted backups in the same publicly accessible location.
11. How to Restore a MySQL Backup
A backup is only useful if you can restore it.
First, download the backup from S3:
aws s3 cp \
s3://devbyte-database-backups/mysql/YOUR_HOSTNAME/YOUR_BACKUP.sql.gz \
/tmp/mysql-restore.sql.gzVerify the compressed file:
gzip -t /tmp/mysql-restore.sql.gzCreate a separate test database:
mysql -u root -p -e "CREATE DATABASE restore_test;"Restore the SQL dump into the test database:
gzip -dc /tmp/mysql-restore.sql.gz | \
mysql -u root -p restore_testEnter the database password when prompted.
Validate the restored data:
mysql -u root -p -e "SHOW TABLES FROM restore_test;"For a stronger test, compare important row counts, validate application queries, and run the application against the restored database in a safe test environment.
Never test restoration by overwriting your production database. Use a separate test database or isolated environment.
For important production systems, define a Recovery Point Objective (RPO)—how much data loss is acceptable—and a Recovery Time Objective (RTO)—how long recovery may take. Daily backups alone may not satisfy a requirement for very low data loss.
12. MongoDB Backup Example
If your application uses MongoDB instead of MySQL, you can use mongodump to create a backup.
For a database reachable through a connection string stored in a protected environment variable:
#!/usr/bin/env bash
set -Eeuo pipefail
umask 077
BACKUP_DIR="/var/backups/mongodb"
S3_BUCKET="s3://devbyte-database-backups"
DB_NAME="my_application"
TIMESTAMP="$(date -u +'%Y-%m-%d_%H-%M-%S')"
BACKUP_PATH="${BACKUP_DIR}/${DB_NAME}_${TIMESTAMP}"
mkdir -p "$BACKUP_DIR"
if [[ -z "${MONGODB_URI:-}" ]]; then
echo "MONGODB_URI is not configured" >&2
exit 1
fi
mongodump \
--uri="$MONGODB_URI" \
--db="$DB_NAME" \
--out="$BACKUP_PATH"
tar -czf "${BACKUP_PATH}.tar.gz" \
-C "$BACKUP_DIR" \
"$(basename "$BACKUP_PATH")"
aws s3 cp \
"${BACKUP_PATH}.tar.gz" \
"${S3_BUCKET}/mongodb/$(basename "${BACKUP_PATH}.tar.gz")" \
--only-show-errors \
--sse AES256
rm -rf -- "$BACKUP_PATH"
rm -f -- "${BACKUP_PATH}.tar.gz"
echo "MongoDB backup uploaded successfully"This example assumes a compatible mongodump version is installed and that the connection string has appropriate access.
Configure MONGODB_URI securely in the execution environment. Do not hardcode credentials in the script or commit them to source control.
For replica sets, sharded clusters, or databases requiring consistent point-in-time recovery, choose a backup method that meets the deployment's consistency and recovery requirements. A basic mongodump job may not be sufficient for every production topology.
Also, the example illustrates the core workflow rather than a complete production-hardened script: add logging, cleanup on failure, integrity checks, retention, and restore testing before relying on it.
13. Common Problems and Solutions
Access Denied When Uploading to S3
Possible causes:
Incorrect AWS credentials.
Missing IAM permissions.
Incorrect bucket name or Region.
Bucket policy restrictions.
Missing KMS permissions when using SSE-KMS.
What to check:
aws sts get-caller-identity
aws s3 ls s3://devbyte-database-backups/Review the error message and the permissions attached to the identity running the backup.
Cron Job Does Not Run
Cron may use a limited environment, and the scheduled job may run under a different user.
Check:
sudo crontab -l
sudo systemctl status cronAlso verify file permissions, executable status, absolute paths, and the server timezone.
MySQL Authentication Fails
Verify that:
The MySQL configuration file exists.
The file is readable by the script's execution user.
The database username and password are correct.
The user has the required backup privileges.
The configured host and port are correct.
Run the backup command manually using the same user that Cron will use.
Backup Upload Succeeds but the File Cannot Be Restored
A successful upload only confirms that the transfer completed. The dump may still be incomplete, incompatible with the target database version, or unsuitable for restoring the required database objects.
Test the compressed file and perform regular restore drills in an isolated environment.
14. Recommended Backup Strategy
For a typical small application running on a VPS, a reasonable starting plan might be:
Component | Example Configuration |
|---|---|
Backup frequency | Daily |
Scheduled time | 2:00 AM server time |
Local retention | 7 days |
Remote storage | Private Amazon S3 bucket |
Encryption | S3-managed encryption or approved KMS configuration |
Monitoring | Alerts for failures and stale backups |
Restore testing | Regular scheduled recovery drills |
Long-term retention | S3 Lifecycle policy based on requirements |
This configuration is a starting point, not a universal standard. High-traffic applications, financial systems, and other critical services may require more frequent backups, transaction logs, point-in-time recovery, or database-native backup services.
Conclusion
Automating database backups with Bash, Cron, and Amazon S3 is an effective way to improve data protection without building a complex backup system from scratch.
With a carefully configured script, scheduled execution, secure credentials, private S3 storage, retention policies, monitoring, and regular restore tests, developers can reduce manual work and improve recovery readiness.
The most important lesson is simple: a backup is not reliable until you have verified that it can be restored.
Start with a test database, confirm that the backup reaches S3, perform a restore in an isolated environment, and only then use the workflow for production data.
Frequently Asked Questions
1. Can I automate database backups without a paid backup service?
Yes. You can schedule backup scripts using Cron and upload the files to Amazon S3. However, S3 storage, requests, data transfer, and related AWS resources may incur charges.
2. How often should database backups run?
It depends on your application's data-loss tolerance. Daily backups may be enough for some small applications, while critical applications may need hourly backups, continuous log archiving, or point-in-time recovery.
3. Are database backups stored in S3 secure?
They can be secure when the bucket is private, access is restricted, encryption is enabled, credentials are protected, and retention and deletion controls are configured correctly.
4. Can the same approach work with PostgreSQL?
Yes. PostgreSQL supports tools such as pg_dump and pg_dumpall. The backup format, authentication, consistency requirements, and restoration commands differ from MySQL, so the script must be adapted accordingly.
5. What happens if the server fails before uploading a backup?
Any backup that exists only on that server may be lost. Uploading backups to a separate storage system such as S3 helps protect against local server failure. For critical systems, consider additional independent recovery copies and monitoring to detect missed uploads.
6. Does a successful S3 upload guarantee a valid backup?
No. It confirms that the object was uploaded, not that the database can be recovered. Validate the file and periodically restore it into an isolated environment.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


