mongodb backuscript
#Add the following line to run the backup daily at 2:00 AM:
0 2 * * * /home/sas/mongo_backup.sh
#!/bin/bash
# MongoDB Daily Backup Script
# Place in /home/sas/mongo_backup.sh and make executable
# ------------------------------
# CONFIGURATION
# ------------------------------
BACKUP_DIR="/usr/src/mongodb" # Base backup directory
RETENTION_DAYS=7 # Keep backups for 7 days
MONGODUMP_CMD="mongodump" # Path to mongodump (if not in $PATH)
LOG_FILE="/var/log/mongo_backup.log" # Log file
TIMESTAMP=$(date +"%Y%m%d_%H%M%S") # Timestamp for this backup
BACKUP_PATH="$BACKUP_DIR/$TIMESTAMP" # Full backup path
# ------------------------------
# FUNCTIONS
# ------------------------------
log() {
echo "$(date +"%Y-%m-%d %H:%M:%S") - $1" | tee -a "$LOG_FILE"
}
# ------------------------------
# MAIN SCRIPT
# ------------------------------
# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"
log "Starting MongoDB backup to $BACKUP_PATH"
# Run mongodump
if $MONGODUMP_CMD --out "$BACKUP_PATH"; then
log "mongodump succeeded. Compressing..."
# Compress the backup
tar -czf "$BACKUP_PATH.tar.gz" -C "$BACKUP_DIR" "$TIMESTAMP"
if [ $? -eq 0 ]; then
log "Compression successful."
# Remove uncompressed directory
rm -rf "$BACKUP_PATH"
log "Uncompressed backup removed."
else
log "Compression failed. Keeping uncompressed backup."
fi
else
log "mongodump failed. Backup aborted."
exit 1
fi
# Remove backups older than RETENTION_DAYS
log "Cleaning up backups older than $RETENTION_DAYS days"
find "$BACKUP_DIR" -name "*.tar.gz" -type f -mtime +$RETENTION_DAYS -exec rm {} \;
find "$BACKUP_DIR" -type d -mtime +$RETENTION_DAYS -exec rm -rf {} \; 2>/dev/null
log "Backup process completed."
Comments
Post a Comment