MongoDB Backup to S3 on Ubuntu: Automate It with Cron
Set up a MongoDB backup to S3 on Ubuntu with mongodump, gzip archives, and cron. Follow the script, configure retention, and check its limits before deployment.
An off-site backup should not depend on remembering to run a command. My MongoDB backup to S3 setup uses mongodump, a gzip archive, and a daily cron job on Ubuntu. This guide covers the script, AWS access, scheduling, and retention.
The script is a starting point, not a complete recovery plan. It does not verify a restore, detect a missed cron run, or guarantee a consistent snapshot while the database is changing.
Key takeaways
- Create a compressed archive of one MongoDB database and upload it to S3.
- Schedule it for 2 AM IST on a UTC server.
- Configure local cleanup and a separate S3 retention rule.
- Check consistency requirements, test a restore, and add failure alerts before relying on the backup.
Before you start
You need Ubuntu with Snap, MongoDB Database Tools with mongodump available, access to the database, and an S3 bucket. Use a dedicated backup account or role. Configure AWS credentials for the same operating-system user whose crontab will run the script.
This example uses a single database. MongoDB documents how mongodump behaves during writes. Without an appropriate consistency strategy, a live dump can contain data from different points in time. Do not add --oplog blindly to this database-scoped script; review its replica-set and full-dump requirements first.
MongoDB backup to S3: the workflow
MongoDB
↓
mongodump (gzip archive)
↓
AWS S3 upload
↓
Local retention cleanup1. Install AWS CLI on Ubuntu
This script uses the Snap installation of AWS CLI:
sudo snap install aws-cli --classicConfirm that the interactive command is available:
aws --version2. Configure bucket-scoped AWS access
On EC2, prefer an IAM role. If you need an IAM user, create one in the AWS console and configure programmatic access with an access key. Do not give the backup process administrator access.
Use a policy scoped to the backup bucket:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:PutObject", "s3:ListBucket"],
"Resource": [
"arn:aws:s3:::your-bucket-name",
"arn:aws:s3:::your-bucket-name/*"
]
}
]
}Replace the bucket placeholder before attaching the policy. If using an access key, store the secret securely for the next step. This policy covers uploads and listing, not downloads for a restore. Additional permissions may be needed for your bucket's encryption settings.
3. Configure AWS on the server
aws configureFor an IAM user, enter the credentials and region:
Access Key
Secret Key
Region (e.g. ap-south-1)
Output format: json4. Create and test the backup script
nano ~/mongo-backup.shSet the database URI and bucket in this script before running it. The local cleanup command deletes matching old files from the backup directory, so keep that directory dedicated to backups.
#!/bin/bash
# === MongoDB Daily Backup Script ===
set -e
MONGO_URI="mongodb://localhost:27017/mydatabase"
BACKUP_DIR="$HOME/bkp"
DATE=$(date +"%Y-%m-%d_%H-%M-%S")
S3_BUCKET="s3://your-bucket-name"
BACKUP_NAME="backup-$DATE.gz"
RETENTION_DAYS=7
LOG_FILE="$HOME/mongo-backup.log"
mkdir -p "$BACKUP_DIR"
echo "Starting backup: $DATE" >> "$LOG_FILE"
# Dump database (mongodump ships in cron's default PATH)
mongodump --uri="$MONGO_URI" \
--archive="$BACKUP_DIR/$BACKUP_NAME" --gzip >> "$LOG_FILE" 2>&1
# Upload to S3 via Snap's canonical app name (no PATH gymnastics required)
snap run aws-cli.aws s3 cp "$BACKUP_DIR/$BACKUP_NAME" "$S3_BUCKET/" >> "$LOG_FILE" 2>&1
# Cleanup old local backups
find "$BACKUP_DIR" -type f -mtime +$RETENTION_DAYS -delete
echo "Backup completed successfully: $BACKUP_NAME" >> "$LOG_FILE"Why
snap run aws-cli.aws? Cron has a smaller environment than your interactive shell. This calls the Snap app by its qualified name rather than relying on the interactiveawsalias.The commands
snapandmongodumpmust still be available in cron's PATH, so test with the actual cron user. If you installed AWS CLI another way, adapt the invocation to that installation.
Make the script executable and run it manually:
chmod +x ~/mongo-backup.sh
~/mongo-backup.shCheck the log and confirm that the archive reached the intended bucket. A successful upload alone does not prove that the data can be restored.
5. Schedule the cron job for 2 AM IST
If your server is on UTC, 2 AM IST = 20:30 UTC the previous day.
crontab -eAdd:
30 20 * * * $HOME/mongo-backup.sh >> $HOME/mongo-backup.log 2>&1Cron's command shell expands $HOME. The schedule uses the server's cron time zone, so confirm that it is UTC before copying this entry.
6. Set S3 retention separately
Local cleanup does not remove S3 objects. In the S3 console, open the bucket's lifecycle settings and add an expiration rule, for example after 30 days. Choose the period around your recovery needs. If versioning is enabled, account for noncurrent versions too.
Checks before you rely on the backup
- Use an IAM role on EC2 and restrict access to the backup bucket.
- Review encryption and versioning settings with retention in mind.
- Confirm that local cleanup retains the history you expect.
finduses file-age rules, not a calendar-based count of seven daily backups. - Check archive freshness separately. A job that never starts cannot report its own failure.
- Run a restore drill and add alerts for failed dumps and uploads.
FAQ
Can mongodump run while MongoDB is serving traffic?
Yes, but a live dump is not automatically a point-in-time backup. Check MongoDB's documented consistency requirements for your deployment and write workload. Moving reads to a secondary does not solve that problem by itself.
How much S3 storage will the archives use?
Measure several real archives. Compression depends on the data, so there is no useful fixed ratio to promise. Multiply your measured archive size by the number of retained backups, then check storage and transfer costs for your region.
Why use mongodump rather than mongoexport?
mongodump produces BSON data and metadata intended for use with mongorestore. MongoDB explicitly says that mongoexport is not a backup tool. Use exports for data exchange, not as a substitute for a restore-tested backup.
Can I use this with Docker or Atlas?
The same dump-and-upload pattern can work, but the connection setup changes. For Docker, run the tools where they can reach the database. For Atlas, check network access, authentication, supported features, and Database Tools compatibility before using an SRV URI.
How do I restore a gzip archive?
Use mongorestore with both the archive and gzip options, and restore to a scratch namespace first. The MongoDB restore guide covers the download, namespace mapping, and verification steps.
Add alerts, then test recovery
The Amazon SES failure-alert guide adds email attempts when mongodump or the S3 upload fails. It is one monitoring layer, not proof that every scheduled run completed.
Then restore a backup from S3. Check the data before you call the backup ready.