Skip to content

Instantly share code, notes, and snippets.

@dgacitua
Created July 27, 2021 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgacitua/eafe1e0b95732dc792acaea299d03ea0 to your computer and use it in GitHub Desktop.
Save dgacitua/eafe1e0b95732dc792acaea299d03ea0 to your computer and use it in GitHub Desktop.
MongoDB backup cronjob (files will be saved on ~/backups)
# Run "crontab -e" and add the uncommented lines at the end of the file
# Be sure to put the absolute path of mongobackup.sh
# This job will run every Saturday at 01:00
0 1 * * 6 ./home/myuser/mongobackup.sh
#!/bin/sh
set -e
# Be sure to edit NAME, MONGOHOST and MONGODATABASE to suit your needs
ORIG=$(pwd)
FILE=$(date +%F)
DEST=$HOME/backups
TEMP=$DEST/temp
LOGF=$DEST/backup.log
NAME=myproject
MONGOHOST=localhost:27017
MONGODATABASE=mydatabase
mkdir -p $DEST
echo "*** BACKUP STARTED AT $(date -R) ***" >> $LOGF
echo ">> [$NAME] Creating temp folder" >> $LOGF
mkdir -p $TEMP >> $LOGF 2>&1
echo ">> [$NAME] Backing up MongoDB" >> $LOGF
mongodump -v -h $MONGOHOST -d $MONGODATABASE -o $TEMP >> $LOGF 2>&1
echo ">> [$NAME] Compresssing backup" >> $LOGF
cd $TEMP >> $LOGF 2>&1
tar -zcvf $DEST/$FILE-$NAME.tar.gz * >> $LOGF 2>&1
cd $ORIG >> $LOGF 2>&1
echo ">> [$NAME] Deleting temp folder" >> $LOGF
chmod -R +w $TEMP >> $LOGF 2>&1
rm -rf $TEMP >> $LOGF 2>&1
echo "*** BACKUP ENDED AT $(date -R) ***" >> $LOGF
set +e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment