From dda78da81550b0a196a75a971cbd2cc74dcdfe36 Mon Sep 17 00:00:00 2001 From: knee-cola Date: Sun, 24 Aug 2025 08:13:57 +0000 Subject: [PATCH] backup: write backups to backups/ and rotate (keep 7), gitignore backups/ --- .gitignore | 3 +++ backup.sh | 27 ++++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index f0b378e..9750d07 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,6 @@ mongo-volume # backup files created by backup.sh mongo-volume-backup-*.tar.gz + +# backups directory for mongo-volume tarballs +/backups/ diff --git a/backup.sh b/backup.sh index 87e983c..461cce3 100755 --- a/backup.sh +++ b/backup.sh @@ -1,8 +1,33 @@ +#!/usr/bin/env bash +set -euo pipefail + +# scale down mongo service while we copy its volume docker service scale utility-bills-tracker_mongo=0 +# timestamp for filename TIMESTAMP=$(date +"%Y-%m-%d-%H-%M") -BACKUP_FILE="mongo-volume-backup-$TIMESTAMP.tar.gz" + +# 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 service back up docker service scale utility-bills-tracker_mongo=1