✅ Automated MongoDB backup
✅ Upload to AWS S3
✅ Run daily at 2 AM IST
✅ Retain only last 7 days locally
✅ Production-safe cron execution
MongoDB
↓
mongodump (gzip archive)
↓
AWS S3 upload
↓
Local retention cleanup
We install AWS CLI using Snap:
sudo snap install aws-cli --classic
Verify
aws --version
In Amazon Web Services console:
Go to IAM → Users → Create User
Enable programmatic access
Attach policy:
For quick setup:
AmazonS3FullAccess
For production (recommended), use restricted policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:PutObject",
"s3:ListBucket"
],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::your-bucket-name",
"arn:aws:s3:::your-bucket-name/*"
]
}
]
}
Save:
Access Key
Secret Key
aws configure
Enter:
Access Key
Secret Key
Region (e.g. ap-south-1)
Output format: json
Create file:
nano /home/ubuntu/mongo-backup.sh
Paste:
#!/bin/bash
# === MongoDB Daily Backup Script ===
set -e
MONGO_URI="mongodb://localhost:27017/mydatabase"
BACKUP_DIR="/home/ubuntu/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/ubuntu/mongo-backup.log"
mkdir -p "$BACKUP_DIR"
echo "Starting backup: $DATE" >> "$LOG_FILE"
# Dump database
/usr/bin/mongodump --uri="$MONGO_URI" --archive="$BACKUP_DIR/$BACKUP_NAME" --gzip >> "$LOG_FILE" 2>&1
# Upload to S3
/snap/bin/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"
Make executable:
chmod +x /home/ubuntu/mongo-backup.sh
Test manually:
/home/ubuntu/mongo-backup.sh
If your server is in UTC:
2 AM IST = 20:30 UTC (previous day)
Edit cron:
crontab -e
Add:
30 20 * * * /home/ubuntu/mongo-backup.sh >> /home/ubuntu/mongo-backup.log 2>&1
Go to S3 → Bucket → Management → Lifecycle Rule:
Create rule:
Delete objects after 30 days
This prevents infinite storage growth.
Use IAM role instead of access keys (if running on EC2)
Restrict S3 permissions to specific bucket
Enable S3 versioning
Enable server-side encryption (SSE-S3 or SSE-KMS)
Periodically test restore process
Creating helpful tools and sharing productivity insights to make your work easier.
Convert your selected date into multiple popular date formats — instantly, accurately, and ready to copy.
Discover the simplicity of sending WhatsApp messages without saving phone numbers with Tooloogle's easy-to-use online tool. Instantly message anyone directly on WhatsApp in a hassle-free manner. Ideal for businesses and personal use alike. No registration required. Start messaging now!
Generate Custom QR Codes Easily with Tooloogle's QR Code Generator
Gold Purity calculator helps you calculate the purity of the gold by using the karat rating
Easily convert byte arrays to readable text strings with our efficient online converter tool.