Backup database mongo by crontab

Step 1: Cài đặt crontab

Install Crontab
apt install cron

Step 2: Tạo file tên backup-mongo.sh

backup-mongo.sh
#!/bin/bash

dusage=$(df -Ph | grep -vE '^tmpfs|cdrom' | sed s/%//g | awk '{ if($5 > 90) print $0;}')
fscount=$(echo "$dusage" | wc -l)
if [ $fscount -ge 2 ]; then
echo "$dusage" | mail -s "Disk Space Alert On $(hostname) at $(date)" [email protected]
else
export PATH=/bin:/usr/bin:/usr/local/bin
TODAY=$(date +"%d%b%Y")

######################################################################
######################################################################

DB_BACKUP_PATH='/home/backup/mongo'
MONGO_HOST='localhost'
MONGO_PORT='27017'

AUTH_ENABLED=0
MONGO_USER=''
MONGO_PASSWD=''
DATABASE_NAMES='ALL'
BACKUP_RETAIN_DAYS=1
KEEP_FILE=3

######################################################################
######################################################################

mkdir -p ${DB_BACKUP_PATH}/${TODAY}

AUTH_PARAM=""

if [ ${AUTH_ENABLED} -eq 1 ]; then
AUTH_PARAM=" --username ${MONGO_USER} --password ${MONGO_PASSWD} "
fi

if [ ${DATABASE_NAMES} = "ALL" ]; then
echo "You have choose to backup all databases"
/usr/local/bin/mongodb/mongodump --host ${MONGO_HOST} --port ${MONGO_PORT} ${AUTH_PARAM} --out ${DB_BACKUP_PATH}/${TODAY}/
else
echo "Running backup for selected databases"
for DB_NAME in ${DATABASE_NAMES}; do
/usr/local/bin/mongodb/mongodump --host ${MONGO_HOST} --port ${MONGO_PORT} --db ${DB_NAME} ${AUTH_PARAM} --out ${DB_BACKUP_PATH}/${TODAY}/
done
fi

## DELETE FILE
FILEPATH=$(date +"%d%b%Y" --date="${KEEP_FILE} days ago")

if [ ! -z ${DB_BACKUP_PATH} ]; then
cd ${DB_BACKUP_PATH}
if [ ! -z ${FILEPATH} ] && [ -d ${FILEPATH} ]; then
rm -rf ${FILEPATH}
fi
fi

## ZIP FILE
if [ ! -z ${DB_BACKUP_PATH} ]; then
cd ${DB_BACKUP_PATH}
if [ ! -z ${TODAY} ] && [ -d ${TODAY} ]; then
tar -cvf ${TODAY}.tar ${TODAY}
fi
if [ ! -f "${TODAY}.tar" ]; then
rm -rf ${TODAY}
fi
fi
fi
 
######################### End of script ##############################

Step 3: run: bash backup-mongo.sh

Step 4: edit config: crontab -e