This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
A single Bash script, mongo_backup_manager.sh, that backs up / restores a MongoDB
database running inside a Docker container and optionally syncs the backups to an
AWS S3 bucket. There is no build system, package manager, or test suite — the entire
project is this one script plus its README.md.
chmod +x mongo_backup_manager.sh # once
./mongo_backup_manager.sh help # usage (also the default with no args)
./mongo_backup_manager.sh backup # dump → copy to host → upload to S3 → prune >7d
./mongo_backup_manager.sh list_backups_local
./mongo_backup_manager.sh list_backups_s3
./mongo_backup_manager.sh download_backup <file.gz> # S3 → ./backups_temp/
./mongo_backup_manager.sh restore <file> [src_db src_coll dst_db dst_coll]
./mongo_backup_manager.sh verify <src_db src_coll dst_db dst_coll> # post-restore parity check
./mongo_backup_manager.sh alert [unit] # best-effort failure alert; for systemd OnFailure=Requires a .env file beside the script (the script exits if missing); .env-example
is the committed template (placeholders only — real secrets never committed). Required keys:
CONTAINER_NAME, MONGO_PORT, MONGO_DB_NAME; plus MONGO_USER/MONGO_PASSWORD
unless USE_CREDENTIALS=false; plus S3_BUCKET_NAME/AWS_PROFILE only when USE_REMOTE=true
(remote is off by default — USE_REMOTE defaults to false); plus at least one alert
destination (DISCORD_WEBHOOK_URL, and/or TELEGRAM_BOT_TOKEN+TELEGRAM_CHAT_ID) only when
USE_ALERTS=true (alerting is off by default).
See README.md for the full table and the required IAM policy.
There is no linter configured; if changing the script, validate manually with
bash -n mongo_backup_manager.sh and ideally shellcheck.
set -euo pipefailis on — any unset var or failed command aborts the run. Guard optional vars with${VAR:-}(the script does this consistently).- Three feature flags gate whole code paths, normalized to lowercase at the top:
USE_CREDENTIALS=false→ no--username/--password/--authenticationDatabaseargs are passed tomongodump/mongorestore, and they're dropped fromhealth_check.USE_REMOTE=false→ all S3 upload/download/list/prune calls are skipped, andS3_BACKUP_PATHis never even defined (so don't reference it unconditionally).USE_ALERTS=false(default) → thealertcommand sends nothing, andhealth_checkskips alert-config validation. Whentrue,health_checkrequires a usable destination and thealertcommand actually posts (see the alerting bullet below).
health_checkruns before every command (excepthelpandalert) and builds its required-var list dynamically from the flags above. Adding a new required var means updatingREQUIRED_VARSthere. It also validatesS3_RETENTION_DAYS(when remote) and the alert config (when alerting): a half-configured Telegram (only one of token/chat-id) orUSE_ALERTS=truewith no destination is rejected — never echoing any secret value.- Container-name resolution (
resolve_container):CONTAINER_NAMEmay be an exact name (backward-compatible) or a stable prefix (Coolify regenerates the fullsodax-stateful-mongo-<hash>-<ts>name on every redeploy). Resolved at run time viadocker ps --filter name=(running only). Docker'sname=is an unanchored substring match, so the results are post-processed: an exact{{.Names}}match wins if one is running (so an exact name that's also a substring of another container —mongovsmongo-express— isn't wrongly rejected as ambiguous); otherwise the results are filtered to names that actually start with the configured value (a bare substring likeold-<prefix>-sidecaris not a prefix match, so it can't be silently picked when the real container is down), and exactly one must remain — 0 (nothing up) or >1 (ambiguous) is a hard error, never a guess (wrong container = wrong backup, or on restore a destructive overwrite). It mutates the globalCONTAINER_NAMEin place and is called once from the dispatcher, right afterhealth_check, for backup/restore/verify only — the list/download/alert commands don't touch the container and must not require one to be running. - Auth args are passed as a bash array via
build_mongo_auth_args(a nameref helper), never throughsh -c. This is deliberate — it avoids shell-quoting/injection issues with passwords. Keep new docker exec args in arrays the same way. - Backup flow:
mongodump --archive --gzipwrites inside the container to a bare filename, thendocker cppulls it to./backups/, thendocker exec rm -fdeletes the in-container copy (nothing else would — otherwise dumps pile up in the container's writable layer), then optional S3 upload, then afind -mtime +7prune of localmongo_backup_*.gz(name-restricted so an unrelated.gzin the dir is never deleted). Filenames aremongo_backup_<TIMESTAMP>.gz. Retention runs on both sides: after upload (when remote is on) it also prunes S3 —list-objects-v2under themongodb-backups/prefix, then deletes anymongo_backup_*.gzwhose name-embedded timestamp is older thanS3_RETENTION_DAYS(env var, default7). S3 has no age filter, so it strips each name to its 14-digitYYYYMMDDHHMMSSand integer-compares it against a host-local cutoff built the same way asTIMESTAMP— an integer compare, not a string<(that would be locale-dependent), and names without a full 14-digit stamp are skipped. The S3 prune is best-effort (warns, doesn't abort) since the dump already uploaded; it needss3:ListBuckets3:DeleteObject.S3_RETENTION_DAYS=0skips the S3 prune entirely (an S3 lifecycle policy owns retention instead);health_checkvalidates it as a non-negative integer whenUSE_REMOTE=true. Only the S3 side is configurable — the localfind -mtime +7is still fixed at 7 days.
- Restore flow:
docker cpthe archive into the container's/tmp, thenmongorestore --drop. With no remap args it restores--nsInclude=${MONGO_DB_NAME}.*. With all four remap args it uses--nsInclude/--nsFrom/--nsToto movesrc_db.src_coll → dst_db.dst_coll— and the remap args are all-or-nothing (validated; partial sets error out). The Mongo user needsreadWriteon the destination DB or you get "listCollections requires authentication". - Verify flow:
verifyruns entirely inside the container viadocker exec ... mongosh --eval, reaching both namespaces withgetSiblingDB. The JS canonicalizes each index (stripsv/ns, recursively sorts object keys but preserves the order-sensitivekeyfield; non-plain objects like BSONDate/ObjectIdare serialized withEJSONso distinct scalar values stay distinct), compares the normalized index-set pluscountDocuments, andquit(1)s on any mismatch — the bash wrapper turns that into a non-zero script exit. mongosh uses space-separated auth flags (build_mongosh_auth_args), unlike mongodump/mongorestore which take--flag=val(build_mongo_auth_args). The JS logic lives in a quoted (<<'EOF') heredoc — so the shell does no expansion and the JS may use$/backticks freely — and the four namespace names are prepended as a prelude of JSON-encoded JS string literals (json_str), so a db/collection name containing a quote or backslash can't break or alter the script. Keep that split intact when editing: logic in the quoted heredoc, names via the escaped prelude — never interpolate raw names into the JS. - Directories are all anchored to the script's own location via
SCRIPT_DIR(likeLOG_FILE/ENV_FILE), not the caller's CWD — so they resolve correctly under cron/systemd where CWD is usually$HOME.backups/(local dumps, git-kept but contents gitignored),backups_temp/(S3 downloads land here),logs/(gitignored). Keep new pathsSCRIPT_DIR-anchored too. - Run logging: near the top the script does
exec > >(tee -a "$LOG_FILE") 2>&1, so all stdout+stderr for the run is mirrored intologs/mongo_backup_manager.log(not just the separators) while still reaching the terminal/journal; a process substitution is used (not| tee) to preserve the script's own exit status. Atrap log_run_end EXITwrites the end separator + exit code on every exit path, so early/failed exits are still recorded. - Scheduling:
systemd/mongo-backup.{service,timer}are ready-to-edit units that runbackupon a timer (see README "Scheduling automated backups"). The service isType=oneshotand sets an explicitPATH(cron/systemd start with a minimal one, sodocker/aws/mongoshwouldn't otherwise resolve). - Failure alerting:
mongo-backup.servicehasOnFailure=mongo-backup-alert.service; that companion oneshot runsmongo_backup_manager.sh alert mongo-backup.serviceand posts the failed run's output to Discord and/or Telegram. The excerpt comes from the on-disk run log ($LOG_FILE, which every non-alert run mirrors viatee), sliced from the LASTRun started at …header to EOF — so it's exactly the run that just failed, with no systemd-journal coupling (no--invocationversion gate, no post-exitInvocationIDlookup, nosystemd-journalread permission) and no bleed from a prior successful run. The block is trusted only if THIS failure just wrote it — both the file mtime is fresh (withinALERT_LOG_MAX_AGE_SECS, default 300s) and the block carries theRun FAILED during stage: …marker (the EXIT trap writes it on any non-zero exit). Freshness catches a stale block from a log the run could no longer append to — even one that ended in an earlierRun FAILED(the marker alone can't tell that apart); the marker catches a fresh-but-incomplete block from a run killed before the trap (SIGKILL/OOM). Either miss → a plainjournalctl -u <unit>tail fallback, so the alert always reports the current failed run, never a stale one. The per-destination char-cap truncation keeps the tail of the excerpt (not the head), so theRun FAILED during stage: …line — always last — survives even a verbose late-stage failure. (Both truncations only tail when the char budget is positive, so a pathologically long title can't trip the${var: -0}whole-string return.) It runs as the same unprivileged user as the backup, not root — the scriptsources.env, so a root alert + a backup-user-writable.envwould be a local privilege escalation. As a backstop the script refuses to source a non-root-owned or group/other-writable.envwhen it is run as root (id -u==0 check before thesource). Reading the run log needs only read access tologs/(the same user owns it); thesystemd-journalgroup is now only relevant to the journal fallback. A stage marker makes the alert unambiguous:stage "<name>"sets a globalCURRENT_STAGEand echoes>>> STAGE: <name>into the log/journal at each transition. The dispatcher runsresolve containerfirst (shared by backup/restore/verify); then each command advances it — backup:prepare dump → mongodump → copy dump to host → S3 upload → S3 prune → local prune; restore:restore preflight → copy archive to container → mongorestore; verify:verify. Thelog_run_endEXIT trap printsRun FAILED during stage: <CURRENT_STAGE>on a non-zero exit, so the run-log tail the alert forwards names the culprit (every path advances pastresolve container, so a failure is never misattributed to name resolution). Thealertcommand is best-effort by contract: it never runshealth_check/resolve_container(it fires because the backup broke, maybe because the container is gone), each destination is attempted independently, a failed send only warns, and it always returns 0 — an alert hiccup must not add a scary secondary failure. Secrets are never echoed and curl output is discarded so the webhook URL / bot token can't leak into the log. Discord JSON is built withjqwhen present, else the in-scriptjson_escape_body(which, unlikejson_str, also escapes newlines/tabs); Telegram usescurl --data-urlencode, no JSON. .env,*.gz, and backup dir contents are all gitignored — never commit them..env-example(placeholders only) is committed as the template; keep it in sync when adding/removing env vars, but never put a real secret in it.
Define a function, then add a case branch in the dispatcher at the bottom that calls
health_check (if it touches Mongo/S3) and forwards positional args as "${2:-}" etc.
Also add a line to help().
Read
~/CLAUDE.md→ "Shared dev-server resource policy" first. It definesdev-status, the go/no-go thresholds (RAM < 8 GiB, swap > 8 GiB, load > 20, another heavy job running) and theheavy-runlock. This section only maps that policy onto this repo.These are instructions for which commands an interactive AI agent runs on this dev box. They change nothing for the scheduled systemd timers or for developers, and
mongo_backup_manager.sh,setup_schedule.sh, thesystemd/units, and.envmust never be edited to enforce them.
Package manager: none — pure Bash. No Node, no npm/pnpm, no Python.
Test runner: none — no Vitest, no Jest, no test suite. Per Running above, validation is bash -n mongo_backup_manager.sh and ideally shellcheck.
Syntax and lint checks are trivial, as are the read-only listings:
bash -n mongo_backup_manager.sh
shellcheck mongo_backup_manager.sh
./mongo_backup_manager.sh help
./mongo_backup_manager.sh list_backups_local
./mongo_backup_manager.sh list_backups_s3These are not CPU-heavy, but they are long-running and disk/IO-heavy (mongodump, gzip, multi-GB copies in and out of backups/). heavy-run's ionice -c2 -n7 is exactly what keeps them from starving the other agent's build, and the lock stops two dumps overlapping. Give them a generous timeout — a real dump can exceed 20 minutes:
heavy-run timeout 60m ./mongo_backup_manager.sh backup
heavy-run timeout 60m ./mongo_backup_manager.sh download_backup <file.gz>
heavy-run timeout 60m ./mongo_backup_manager.sh restore <file> [src_db src_coll dst_db dst_coll]Before running any of these, get explicit user confirmation. They are state-changing and outward-facing — backup uploads to S3 and prunes, restore writes to a live MongoDB — so Golden Rule 3 in ~/CLAUDE.md applies on top of the resource rules. Check free disk (df -h) as well as dev-status: this repo's failure mode is filling the disk, not exhausting RAM.