So you need to backup your MongoDB database over SSH? You’re in the right place! We’ll go through a bunch of different ways to do this, from quick one-liners to fully automated scripts. Pick whatever works best for your situation.
Whether you’re managing a single server or dealing with a whole fleet of databases, having a solid backup strategy is absolutely crucial. I mean, we’ve all heard those horror stories about lost data, right? The good news is that MongoDB makes it pretty straightforward to create backups, and when you combine it with SSH, you can automate the whole thing and sleep better at night.
In this guide, we’ll cover everything from the simplest possible backup command to full-blown automated scripts with rotation policies. We’ll look at different approaches depending on your needs – maybe you just want to quickly grab a copy of your database, or maybe you need nightly automated backups with verification and cloud storage. Whatever your situation, we’ve got you covered.
The cool thing about doing backups via SSH is that you can manage everything remotely. No need to log into each server manually – you can trigger backups from your laptop, automate them with cron jobs, or even stream the data directly to your local machine without using any storage on the remote server. Pretty neat, right?
Before we dive in, if you want to go deeper into MongoDB’s backup concepts or need the official documentation, here are some great resources:
- MongoDB Official Documentation: https://docs.mongodb.com/manual/core/backups/ – The complete guide to MongoDB backup strategies
- mongodump reference: https://docs.mongodb.com/database-tools/mongodump/ – Everything about the mongodump command we’ll be using
- mongorestore reference: https://docs.mongodb.com/database-tools/mongorestore/ – How to restore your backups when you need them
Alright, let’s get into it!
Method 1: Simple mongodump via SSH
The Basic Approach
This is the straightforward way – SSH into your server, dump the database, compress it, and copy it back to your local machine:
|
1 2 3 4 |
ssh user@remote-server "mongodump --out=/tmp/backup && tar -czf /tmp/mongodb-backup.tar.gz /tmp/backup" scp user@remote-server:/tmp/mongodb-backup.tar.gz ./local-backup/ |
If You Need Authentication
Got username/password protection on your MongoDB? No problem, just add the auth params:
|
1 2 3 4 5 6 |
ssh user@remote-server "mongodump --host localhost --port 27017 \ --username admin --password 'yourpassword' \ --authenticationDatabase admin \ --out=/tmp/backup" |
Method 2: Direct Backup to Local Machine
Stream it directly (my favorite!)
Why store the backup on the remote server at all? Just pipe it straight to your local machine. This is super clean and doesn’t eat up space on your server:
|
1 2 3 |
ssh user@remote-server "mongodump --archive --gzip" > mongodb-backup-$(date +%Y%m%d).gz |
Just want one database?
Easy, just specify which one:
|
1 2 3 |
ssh user@remote-server "mongodump --db=mydb --archive --gzip" > mydb-backup-$(date +%Y%m%d).gz |
Method 3: Automated Backup Script
Set it and forget it
Alright, let’s get fancy. Here’s a proper backup script you can throw on your server. It’ll handle everything – compression, cleanup of old backups, the works.
Save this as /home/user/backup_mongodb.sh:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#!/bin/bash # Configuration BACKUP_DIR="/var/backups/mongodb" MONGO_HOST="localhost" MONGO_PORT="27017" MONGO_USER="admin" MONGO_PASS="yourpassword" TIMESTAMP=$(date +"%Y%m%d_%H%M%S") BACKUP_NAME="mongodb_backup_$TIMESTAMP" RETENTION_DAYS=7 # Create backup directory mkdir -p $BACKUP_DIR # Perform backup mongodump --host $MONGO_HOST \ --port $MONGO_PORT \ --username $MONGO_USER \ --password "$MONGO_PASS" \ --authenticationDatabase admin \ --out=$BACKUP_DIR/$BACKUP_NAME \ --gzip # Create compressed archive cd $BACKUP_DIR tar -czf ${BACKUP_NAME}.tar.gz $BACKUP_NAME rm -rf $BACKUP_NAME # Remove old backups find $BACKUP_DIR -name "mongodb_backup_*.tar.gz" -mtime +$RETENTION_DAYS -delete echo "Backup completed: ${BACKUP_NAME}.tar.gz" |
Make it executable:
|
1 2 3 |
chmod +x /home/user/backup_mongodb.sh |
Schedule it with cron
Want this to run every night at 2 AM? Add this to your crontab:
|
1 2 3 |
0 2 * * * /home/user/backup_mongodb.sh >> /var/log/mongodb_backup.log 2>&1 |
Method 4: Local Script to Pull Backups
Here’s a script for your local machine that’ll trigger the remote backup and then pull it down. Pretty handy if you want to control everything from your laptop.
Save this as pull_mongodb_backup.sh on your local machine:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#!/bin/bash # Configuration REMOTE_USER="user" REMOTE_HOST="remote-server.com" REMOTE_BACKUP_DIR="/var/backups/mongodb" LOCAL_BACKUP_DIR="./mongodb-backups" RETENTION_DAYS=30 # Create local backup directory mkdir -p $LOCAL_BACKUP_DIR # Trigger remote backup echo "Creating backup on remote server..." ssh $REMOTE_USER@$REMOTE_HOST "/home/user/backup_mongodb.sh" # Get latest backup filename LATEST_BACKUP=$(ssh $REMOTE_USER@$REMOTE_HOST "ls -t $REMOTE_BACKUP_DIR/mongodb_backup_*.tar.gz | head -1") # Download backup echo "Downloading backup..." scp $REMOTE_USER@$REMOTE_HOST:$LATEST_BACKUP $LOCAL_BACKUP_DIR/ # Remove old local backups find $LOCAL_BACKUP_DIR -name "mongodb_backup_*.tar.gz" -mtime +$RETENTION_DAYS -delete echo "Backup downloaded successfully to $LOCAL_BACKUP_DIR" |
Method 5: Using SSH Keys for Automation
Ditch the passwords
If you haven’t set up SSH keys yet, do it now. You’ll thank me later when you’re not typing passwords all the time:
|
1 2 3 |
ssh-keygen -t rsa -b 4096 -C "mongodb-backup" |
Copy it to your server
|
1 2 3 |
ssh-copy-id user@remote-server |
Now it’s smooth sailing
Backups without password prompts? Yes please:
|
1 2 3 |
ssh user@remote-server "mongodump --archive --gzip" > backup.gz |
Method 6: Backup Specific Collections
Don’t need the whole database? Just grab what you need:
|
1 2 3 4 5 6 7 8 9 10 |
# Backup single collection ssh user@remote-server "mongodump --db=mydb --collection=users --archive --gzip" > users-backup.gz # Backup multiple specific collections ssh user@remote-server "mongodump --db=mydb \ --collection=users \ --collection=orders \ --archive --gzip" > selected-backup.gz |
Method 7: Incremental Backup using Oplog
Got a replica set? You can do point-in-time backups with the oplog. This is pretty advanced stuff, but super useful:
|
1 2 3 4 5 6 7 8 9 |
# Initial full backup ssh user@remote-server "mongodump --oplog --archive --gzip" > full-backup.gz # Incremental oplog backup ssh user@remote-server "mongodump --db local --collection oplog.rs \ --query '{\"ts\":{\"\$gt\":Timestamp(1234567890, 1)}}' \ --archive --gzip" > oplog-incremental.gz |
Restore Examples
Okay, so you’ve got your backup. Now how do you actually use it? Here are the most common scenarios:
Basic restore
|
1 2 3 |
mongorestore --archive=backup.gz --gzip |
Just restore one database
|
1 2 3 |
mongorestore --archive=backup.gz --gzip --nsInclude="mydb.*" |
Push it to a remote server
|
1 2 3 |
cat backup.gz | ssh user@remote-server "mongorestore --archive --gzip" |
Best Practices
Look, I know best practices can sound boring, but trust me – follow these and you’ll avoid a lot of headaches:
1. Security
- Use SSH keys instead of passwords
- Store credentials in environment variables or secure vaults
- Encrypt backups at rest
- Use strong authentication for MongoDB
2. Storage
- Keep backups on separate physical/virtual infrastructure
- Implement 3-2-1 backup rule (3 copies, 2 different media, 1 offsite)
- Monitor backup storage capacity
3. Testing
- Regularly test restore procedures
- Verify backup integrity
- Document restore time objectives (RTO)
4. Monitoring
- Log all backup operations
- Set up alerts for failed backups
- Track backup sizes and durations
5. Performance
- Schedule backups during low-usage periods
- Consider using secondary replica set members for backups
- Use compression to reduce transfer time and storage
Verification Script
Always verify your backups! Here’s a quick script to check if your backup file is actually good:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#!/bin/bash # Verify backup integrity BACKUP_FILE=$1 if [ -z "$BACKUP_FILE" ]; then echo "Usage: $0 <backup-file.gz>" exit 1 fi # Test archive integrity if gzip -t "$BACKUP_FILE" 2>/dev/null; then echo "✓ Backup file integrity verified" # Show backup contents echo -e "\nBackup contents:" mongorestore --archive="$BACKUP_FILE" --gzip --dryRun 2>&1 | grep "preparing" else echo "✗ Backup file is corrupted!" exit 1 fi</backup-file.gz> |
Troubleshooting
Running into issues? Here are some common problems and how to fix them:
Connection Issues
|
1 2 3 4 5 6 7 |
# Test SSH connection ssh user@remote-server "echo 'Connection successful'" # Test MongoDB connection ssh user@remote-server "mongosh --eval 'db.adminCommand({ping:1})'" |
Permission Issues
Getting “permission denied” errors? Check these:
|
1 2 3 4 5 |
# Ensure backup directory permissions ssh user@remote-server "sudo chown -R mongodb:mongodb /var/backups/mongodb" ssh user@remote-server "sudo chmod 755 /var/backups/mongodb" |
Large Database Backups
Got a huge database? Use nice to keep your server from getting hammered during backup:
|
1 2 3 4 |
# Use compression and nice to reduce system impact ssh user@remote-server "nice -n 19 mongodump --archive --gzip" > backup.gz |
Example Complete Workflow
Here’s everything put together – backup, verify, and optionally upload to cloud storage. Copy this and customize it for your needs:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#!/bin/bash # Complete backup and verification workflow REMOTE="user@remote-server" BACKUP_NAME="mongodb-backup-$(date +%Y%m%d-%H%M%S).gz" LOCAL_DIR="./backups" mkdir -p $LOCAL_DIR echo "Starting MongoDB backup..." ssh $REMOTE "mongodump --archive --gzip" > $LOCAL_DIR/$BACKUP_NAME if [ $? -eq 0 ]; then echo "Backup completed: $BACKUP_NAME" # Verify integrity if gzip -t $LOCAL_DIR/$BACKUP_NAME; then echo "Backup verified successfully" # Upload to S3 or other storage (optional) # aws s3 cp $LOCAL_DIR/$BACKUP_NAME s3://my-backup-bucket/ else echo "ERROR: Backup verification failed!" exit 1 fi else echo "ERROR: Backup failed!" exit 1 fi |
