Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- mkdir /db_backups
- /*
- * Step 1: Write the Script
- * Now that that’s out of the way, we’re going to write a little shell script that creates a
- * directory for the current day, then dumps MongoDB into it. That script looks like this
- */
- #!/bin/sh
- DIR=`date +%m%d%y`
- DEST=/db_backups/$DIR
- mkdir $DEST
- mongodump -h <your_database_host> -d <your_database_name> -u <username> -p <password> -o $DEST
- /*
- Step 2: Set Up cron to Run the Script Nightly
- Now that we have our backup script ready to roll,
- we just need to get it running nightly to perform the backups.
- This is easily done by using cron to run the script.
- On your server, simply open the crontab like this:
- */
- sudo crontab -e
- 45 1 * * * ../../scripts/db_backup.sh
- /////////////////////////////////////////////////////////////////////////////
- OR
- vi mongobackup.sh
- /////////////////////////////////////////////////////////////////////////////
- #!/bin/sh
- #=====================================================================
- # Set the following variables as per your requirement
- #=====================================================================
- # Database Name to backup
- MONGO_DATABASE="mydb"
- # Database host name
- MONGO_HOST="127.0.0.1"
- # Database port
- MONGO_PORT="27017"
- # Backup directory
- BACKUPS_DIR="/var/backups/$MONGO_DATABASE"
- # Database user name
- DBUSERNAME="username"
- # Database password
- DBPASSWORD="passw0rd"
- # Authentication database name
- DBAUTHDB="admin"
- # Days to keep the backup
- DAYSTORETAINBACKUP="14"
- #=====================================================================
- TIMESTAMP=`date +%F-%H%M`
- BACKUP_NAME="$MONGO_DATABASE-$TIMESTAMP"
- echo "Performing backup of $MONGO_DATABASE"
- echo "--------------------------------------------"
- # Create backup directory
- if ! mkdir -p $BACKUPS_DIR; then
- echo "Can't create backup directory in $BACKUPS_DIR. Go and fix it!" 1>&2
- exit 1;
- fi;
- # Create dump
- mongodump -d $MONGO_DATABASE --username $DBUSERNAME --password $DBPASSWORD --authenticationDatabase $DBAUTHDB
- # Rename dump directory to backup name
- mv dump $BACKUP_NAME
- # Compress backup
- tar -zcvf $BACKUPS_DIR/$BACKUP_NAME.tgz $BACKUP_NAME
- # Delete uncompressed backup
- rm -rf $BACKUP_NAME
- # Delete backups older than retention period
- find $BACKUPS_DIR -type f -mtime +$DAYSTORETAINBACKUP -exec rm {} +
- echo "--------------------------------------------"
- echo "Database backup complete!"
- step 2
- chomd +x mongobackup.sh
- step3
- crontab -e
- step4 Enter
- 00 00 * * * /path/to/script/mongobackup.sh
Add Comment
Please, Sign In to add comment