Shell Script to Backup MongoDB Database
Creating a shell script for backing up a MongoDB database can automate the process and save time. Below is a simple shell script that uses mongodump
to back up a MongoDB database and store the backup in a specific directory.
1. Create the Shell Script
Open a terminal and create a new script file. You can name it
backup_mongo.sh
:Open the script file in your preferred text editor (e.g.,
nano
):Add the following content to the script:
4. Explanation of the Script
MONGO_HOST
: The MongoDB server's hostname or IP address (default is127.0.0.1
for local MongoDB).MONGO_PORT
: The port MongoDB is listening on (default is27017
).MONGO_DB
: The name of the database you want to back up (e.g.,blogDB
).BACKUP_DIR
: The directory where backups will be stored. Modify it to your desired path.DATE
: A timestamp to make each backup folder unique.mongodump
: The command to create the backup, which includes the database name and backup location.- The script checks if
mongodump
was successful by inspecting the exit status ($?
). If the command returns0
, it means success.
5. Make the Script Executable
After saving the file, make the script executable by running the following command:
6. Run the Script
Now, you can run the script to back up your MongoDB database:
7. Verify the Backup
Check the BACKUP_DIR
directory for the backup files. The backup should be stored in a folder with the current date and time in the directory you specified ($BACKUP_DIR/$DATE
).
8. Automate the Backup (Optional)
To automate the backup process, you can schedule the script to run at specific intervals using cron jobs.
Open the crontab editor:
Add a cron job to run the script every day at midnight (or adjust the timing as needed):
This will execute the backup script every day at 12:00 AM.
9. Conclusion
- Created a shell script to back up a MongoDB database automatically.
- Scheduled backups using
cron
for automation. - The backup is stored with a timestamp, ensuring unique backup folders for each run.
Would you like more help on scheduling backups or any specific customizations for your script? 🚀