#!/usr/bin/env bash set -euo pipefail # Configuration MONGO_SERVICE="mongo" COMPOSE_FILE="docker-compose-standalone.yaml" # stop mongo container while we copy its volume docker compose -f "$COMPOSE_FILE" stop "$MONGO_SERVICE" # timestamp for filename TIMESTAMP=$(date +"%Y-%m-%d-%H-%M") # backup directory and retention (can be overridden via env) BACKUP_DIR="${BACKUP_DIR:-backups}" KEEP="${KEEP:-7}" mkdir -p "$BACKUP_DIR" BACKUP_FILE="$BACKUP_DIR/mongo-volume-backup-$TIMESTAMP.tar.gz" sudo tar -czvpf "$BACKUP_FILE" mongo-volume # rotate old backups: keep only the newest $KEEP files if [ "$KEEP" -gt 0 ]; then # gather files sorted newest-first mapfile -t files < <(ls -1t "$BACKUP_DIR"/mongo-volume-backup-*.tar.gz 2>/dev/null || true) if [ "${#files[@]}" -gt "$KEEP" ]; then for f in "${files[@]:$KEEP}"; do echo "Removing old backup: $f" rm -f -- "$f" done fi fi # bring mongo container back up docker compose -f "$COMPOSE_FILE" start "$MONGO_SERVICE"