Automate MongoDB Backups on Your VPS Using Cron Jobs

Aamir Khan
0
Automate MongoDB Backups on Your VPS Using Cron Jobs

Automate MongoDB Backups on Your VPS Using Cron Jobs

If you're self-hosting your full-stack app with MongoDB on a VPS, automated backups are not just a nice-to-have — they’re essential. In this post, I’ll show you how to set up simple yet reliable MongoDB backups using cron and mongodump.

This guide is perfect for junior devs or self-taught coders who’ve deployed apps using the MERN stack or similar stacks and want to protect their production data.

🔍 Why Automate MongoDB Backups?

  • 💥 Avoid data loss due to VPS crashes, disk failures, or accidental deletes
  • 📅 Keep consistent snapshots of your production database
  • 🧘🏽‍♂️ Free your mind from manual backup routines

⚙️ Prerequisites

  • A running VPS with Ubuntu (or Debian)
  • MongoDB installed and running
  • Basic terminal skills (SSH access to your VPS)

🧱 Step-by-Step: Automating MongoDB Backups

Step 1: Create Backup Script

Create a shell script that runs mongodump and stores the dump with a timestamped folder.

sudo nano /opt/mongodb_backup.sh

Paste the following code:

#!/bin/bash

TIMESTAMP=$(date +%F-%H-%M)
BACKUP_DIR="/var/backups/mongodb"
MONGO_DB="your_database_name"

mkdir -p $BACKUP_DIR
mongodump --db $MONGO_DB --out $BACKUP_DIR/$TIMESTAMP

# Optional: delete backups older than 7 days
find $BACKUP_DIR -type d -mtime +7 -exec rm -rf {} \;

Make the script executable:

sudo chmod +x /opt/mongodb_backup.sh

Step 2: Schedule with Cron

Now, let’s automate this script using cron. Open the crontab editor:

crontab -e

Add the following line to run the backup every night at 2 AM:

0 2 * * * /opt/mongodb_backup.sh >> /var/log/mongodb_backup.log 2>&1

✅ Verify It Works

Run the script manually to confirm:

sudo /opt/mongodb_backup.sh

Check the output directory:

ls /var/backups/mongodb

🔁 Optional: Compress and Upload to Cloud Storage

For extra safety, you can zip the backups and upload them to S3, Google Drive, or Dropbox using CLI tools.

🔗 Related: Hosting Your MongoDB

If you're not sure how to host MongoDB on your VPS, read: How to Deploy MongoDB on VPS (Beginner’s Guide)

🧰 Helpful Tools & Resources

📌 Conclusion

That’s it! Now your MongoDB is backed up every night without you lifting a finger. This small setup can save your project from major headaches later.

💬 Comment below if you’ve used this or have any improvements. Or better yet, try this setup in your next project and tell me how it went!

💖

Enjoyed the Post?

If my blog helped you, please consider supporting me!

Support Me 💖

Post a Comment

0 Comments

Hi Everyone, please do not spam in comments.

Post a Comment (0)

Made with Love by

Welcome to Code Journey with Aamir – your one-stop hub for full-stack development tutorials, projec…