Here's a cleaner, blog-friendly version that follows the same flow as your original script, with numbered steps. You can paste this directly into your blog content, then insert code blocks where needed.
🚀 Step 1: Create the Backup Script
Create a new file named backup.sh inside the /home/ubuntu directory.
This script will automate the complete MongoDB backup process, including creating a database dump, compressing it, uploading it to Amazon S3, and cleaning up temporary files.
📦 Step 2: Install AWS CLI
Install the AWS Command Line Interface (AWS CLI) on your Ubuntu server.
This tool is required to upload backup files to your Amazon S3 bucket.
Command
sudo apt-get install awscli
🔐 Step 3: Configure IAM Role
Create an IAM Role with permission to access Amazon S3 and attach it to your EC2 instance.
Using an IAM Role is the recommended approach because it eliminates the need to store AWS Access Keys on your server.
Make sure the role has permission to:
- Read from Amazon S3 (if needed)
- Upload objects to Amazon S3
- List bucket contents
🗄️ Step 4: Configure Database Details
Update the following values inside the backup script before running it.
- HOST → MongoDB server hostname or IP address.
- DBNAME → Name of the MongoDB database.
- BUCKET → Amazon S3 bucket where backups will be stored.
- USER → Linux user running the script.
Using a MongoDB secondary node is recommended in production environments to reduce load on the primary database.
☁️ Step 5: Create an Amazon S3 Bucket
Create a dedicated Amazon S3 bucket to store your MongoDB backups.
For better storage management, configure an S3 Lifecycle Policy to automatically delete backup files after a specific number of days (for example, 30 or 90 days).
This helps reduce storage costs while keeping your backups organized.
💻 Step 6: Add the Backup Script
Copy and paste the MongoDB backup script into the backup.sh file.
➡️ Insert your Shell Script Code Block here
✅ Step 7: Make the Script Executable
Grant execute permission to the script.
Command
chmod +x backup.sh
▶️ Step 8: Test the Backup Script
Run the script manually to verify that it works correctly.
Command
./backup.sh
If everything is configured correctly, the script will:
- 📦 Create a MongoDB database dump
- 🗜️ Compress the backup
- ☁️ Upload it to Amazon S3
- 🧹 Remove temporary files
- ✅ Display a success message
⏰ Step 9: Automate Daily Backups Using Cron
To run the backup automatically every day at midnight, open the Cron editor.
Command
crontab -e
Add the following Cron entry:
0 0 * * * /home/ubuntu/backup.sh > /home/ubuntu/backup.log
This schedule executes the backup script every day at 12:00 AM and stores the execution logs in backup.log.
Your MongoDB backup process is now fully automated.


Comments
No comments yet. Be the first to share your thoughts.
Leave a comment
Comments are moderated before they appear on this post.