From 036f13878ceae6280cc4779f97db6f609e463e23 Mon Sep 17 00:00:00 2001 From: Tero Date: Thu, 1 Oct 2026 11:53:35 +0300 Subject: [PATCH] first commit --- README.md | 125 ++++++++++++++++ docker-backup.sh | 362 ++++++++++++++++++++++++++++++++++++++++++++++ docker-restore.sh | 85 +++++++++++ 3 files changed, 572 insertions(+) create mode 100644 README.md create mode 100644 docker-backup.sh create mode 100644 docker-restore.sh diff --git a/README.md b/README.md new file mode 100644 index 0000000..50e4b03 --- /dev/null +++ b/README.md @@ -0,0 +1,125 @@ +# ep-docker-backup + +Scripts to back up and restore all Docker containers on a host, including +everything needed to recreate them (config, volumes, bind mounts, and +database dumps), while avoiding container downtime wherever possible. + +## Requirements + +- Linux Docker host with `bash`, `docker`, `tar` +- `jq` (optional but recommended — without it, `recreate.sh` generation and + volume/bind-mount copying are skipped, and only `inspect.json` is saved) + +## Files + +| File | Purpose | +|---|---| +| `docker-backup.sh` | Backs up all (or selected) containers into `.tar.bz2` archives | +| `docker-restore.sh` | Restores a container from an archive produced by `docker-backup.sh` | + +## Backing up + +```bash +chmod +x docker-backup.sh docker-restore.sh +./docker-backup.sh +``` + +### Options + +| Option | Description | Default | +|---|---|---| +| `-o, --output-dir DIR` | Where archives are written | `/var/backups/docker` | +| `-c, --containers LIST` | Comma separated container names to back up | all containers | +| `-k, --keep N` | Keep only the N newest archives per container | `0` (keep all) | +| `-n, --dry-run` | Print the actions that would be taken, without doing them | off | +| `-h, --help` | Show usage | | + +### Examples + +```bash +# Back up every container, keep the 5 most recent archives each +./docker-backup.sh -k 5 + +# Back up only specific containers to a custom location +./docker-backup.sh -o /mnt/nas/docker-backups -c webapp,redis-cache + +# Preview what would happen without touching anything +./docker-backup.sh --dry-run +``` + +Each run produces one archive per container: + +``` +/_backup_.tar.bz2 +``` + +### Archive contents + +``` +/ +├── inspect.json # full `docker inspect` output +├── recreate.sh # generated `docker run` equivalent (requires jq) +├── db/ # native database dump, if a known DB engine was detected +│ └── dump.sql | dump.archive.gz | dump.rdb +├── volumes// # copy of each named volume's contents +└── binds// # copy of each bind-mounted directory +``` + +## How downtime is avoided + +| Container type | Strategy | Downtime | +|---|---|---| +| MySQL / MariaDB | `mysqldump --all-databases` via `docker exec` | None | +| PostgreSQL / PostGIS | `pg_dumpall` via `docker exec` | None | +| MongoDB | `mongodump --archive --gzip` via `docker exec` | None | +| Redis | `BGSAVE`, then copy the resulting `dump.rdb` | None | +| Everything else | Live copy of volumes/bind mounts while the container keeps running | None | + +Database credentials are read automatically from the container's environment +variables (`MYSQL_ROOT_PASSWORD`, `MARIADB_ROOT_PASSWORD`, `POSTGRES_USER`). + +### Forcing a container to stop during backup + +Some containers (e.g. file-based databases with no native dump tool) need to +be stopped briefly for a consistent backup. Opt in per-container with a +label — nothing is stopped unless you explicitly ask for it: + +```bash +docker run -d --label docker-backup.mode=stop ... +``` + +The script stops the container, takes the backup, and restarts it +automatically afterwards (even on failure, via the archive step still +running after restart). + +### Skipping a container + +```bash +docker run -d --label docker-backup.mode=skip ... +``` + +## Restoring + +```bash +./docker-restore.sh /var/backups/docker/webapp_backup_20261001-120000.tar.bz2 --start +``` + +This will: + +1. Extract the archive. +2. Recreate any named volumes and copy their data back in. +3. Print the original host paths for bind mounts so you can copy that data + back manually (host paths are never overwritten automatically). +4. Run `recreate.sh` to recreate the container from its image/config. +5. Print the exact command to restore a database dump if one is present + (DB restores are intentionally left as a manual, reviewed step). +6. Start the container if `--start` was passed. + +## Notes / limitations + +- Designed for a single Docker host (not Swarm/Kubernetes). +- `recreate.sh` covers image, env vars, published ports, restart policy, + network mode, and mounts — review it before running against a different + host, since paths/ports may need adjusting. +- Bind-mount restores are deliberately manual to avoid silently overwriting + unrelated host data. diff --git a/docker-backup.sh b/docker-backup.sh new file mode 100644 index 0000000..eeb0de8 --- /dev/null +++ b/docker-backup.sh @@ -0,0 +1,362 @@ +#!/usr/bin/env bash +# +# docker-backup.sh - Back up all (or selected) Docker containers on a host. +# +# For every container it collects everything needed to restore it later: +# - docker inspect JSON (image, env vars, ports, networks, labels, mounts, restart policy) +# - a generated `recreate.sh` script (docker run equivalent, requires jq) +# - a database dump when a known database engine is detected (mysql/mariadb, +# postgres, mongo, redis) so the DB never has to be stopped +# - a copy of every bind-mounted directory and named volume +# +# Output: /_backup_.tar.bz2 +# +# Usage: +# ./docker-backup.sh [options] +# +# Options: +# -o, --output-dir DIR Where to write the .tar.bz2 archives (default: /var/backups/docker) +# -c, --containers LIST Comma separated container names to back up (default: all containers) +# -k, --keep N Keep only the N newest archives per container (default: 0 = keep all) +# -n, --dry-run Show what would be done without doing it +# -h, --help Show this help +# +# Per-container live/stop behaviour (no label needed for the common cases): +# - Known database images (mysql, mariadb, postgres/postgis, mongo, redis) are +# backed up live via their native dump tool. No downtime required. +# - Any other container is backed up live by copying its volumes/bind mounts +# while it keeps running. +# - To force a container to be stopped for the duration of the backup (e.g. a +# file-based DB with no native dump support), add the label: +# docker-backup.mode=stop +# - To skip a container entirely, add the label: +# docker-backup.mode=skip +# +set -uo pipefail + +SCRIPT_NAME="$(basename "$0")" +OUTPUT_DIR="/var/backups/docker" +CONTAINERS="" +KEEP=0 +DRY_RUN=0 +TIMESTAMP="$(date +%Y%m%d-%H%M%S)" + +log() { printf '[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*"; } +warn() { log "WARNING: $*" >&2; } +err() { log "ERROR: $*" >&2; } +die() { err "$*"; exit 1; } + +usage() { + sed -n '2,/^set -u/p' "$0" | sed 's/^# \{0,1\}//' | sed '$d' +} + +run() { + if [[ "$DRY_RUN" -eq 1 ]]; then + log "DRY-RUN: $*" + else + "$@" + fi +} + +while [[ $# -gt 0 ]]; do + case "$1" in + -o|--output-dir) OUTPUT_DIR="$2"; shift 2 ;; + -c|--containers) CONTAINERS="$2"; shift 2 ;; + -k|--keep) KEEP="$2"; shift 2 ;; + -n|--dry-run) DRY_RUN=1; shift ;; + -h|--help) usage; exit 0 ;; + *) die "Unknown option: $1 (use --help)" ;; + esac +done + +command -v docker >/dev/null 2>&1 || die "docker is required but not found in PATH" +HAVE_JQ=1 +command -v jq >/dev/null 2>&1 || { HAVE_JQ=0; warn "jq not found: recreate.sh generation will be skipped (inspect.json is still saved)"; } + +mkdir -p "$OUTPUT_DIR" || die "cannot create output dir: $OUTPUT_DIR" + +WORK_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/docker-backup.XXXXXX")" +cleanup() { rm -rf "$WORK_ROOT"; } +trap cleanup EXIT + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +get_label() { + local container="$1" key="$2" + docker inspect -f "{{ index .Config.Labels \"${key}\" }}" "$container" 2>/dev/null +} + +get_env_value() { + # get_env_value + local container="$1" var="$2" + docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' "$container" 2>/dev/null \ + | awk -F= -v k="$var" '$1==k { $1=""; sub(/^=/,""); print; exit }' +} + +detect_db_type() { + # Prints one of: mysql postgres mongo redis "" (unknown) + local image="$1" + case "$image" in + *mysql*|*mariadb*) echo "mysql" ;; + *postgres*|*postgis*) echo "postgres" ;; + *mongo*) echo "mongo" ;; + *redis*) echo "redis" ;; + *) echo "" ;; + esac +} + +# --------------------------------------------------------------------------- +# Database dump strategies (all live, no container downtime) +# --------------------------------------------------------------------------- + +dump_mysql() { + local container="$1" outfile="$2" + local pass user + pass="$(get_env_value "$container" MYSQL_ROOT_PASSWORD)" + user="root" + [[ -z "$pass" ]] && pass="$(get_env_value "$container" MARIADB_ROOT_PASSWORD)" + if [[ -z "$pass" ]]; then + warn "[$container] no MYSQL_ROOT_PASSWORD/MARIADB_ROOT_PASSWORD env found, dump may fail" + fi + docker exec "$container" sh -c "exec mysqldump --all-databases -u'$user' -p'$pass' 2>/dev/null" > "$outfile" +} + +dump_postgres() { + local container="$1" outfile="$2" + local user + user="$(get_env_value "$container" POSTGRES_USER)" + [[ -z "$user" ]] && user="postgres" + docker exec -u postgres "$container" sh -c "exec pg_dumpall -U '$user'" > "$outfile" 2>/dev/null \ + || docker exec "$container" sh -c "exec pg_dumpall -U '$user'" > "$outfile" +} + +dump_mongo() { + local container="$1" outfile="$2" + docker exec "$container" sh -c "mongodump --archive --gzip" > "$outfile" +} + +dump_redis() { + local container="$1" outfile="$2" + # trigger a background save, wait for it to finish, then copy the rdb file out + docker exec "$container" redis-cli BGSAVE >/dev/null + local tries=0 + while [[ $tries -lt 30 ]]; do + if docker exec "$container" redis-cli INFO persistence 2>/dev/null | grep -q 'rdb_bgsave_in_progress:0'; then + break + fi + sleep 1 + tries=$((tries + 1)) + done + local rdb_dir + rdb_dir="$(docker exec "$container" redis-cli CONFIG GET dir | tail -n1 | tr -d '\r')" + docker exec "$container" cat "${rdb_dir%/}/dump.rdb" > "$outfile" +} + +backup_database() { + local container="$1" db_type="$2" workdir="$3" + local dumpfile="$workdir/db/dump" + mkdir -p "$workdir/db" + log "[$container] detected database type '$db_type', taking live dump (no downtime)" + case "$db_type" in + mysql) dumpfile="$dumpfile.sql"; run dump_mysql "$container" "$dumpfile" ;; + postgres) dumpfile="$dumpfile.sql"; run dump_postgres "$container" "$dumpfile" ;; + mongo) dumpfile="$dumpfile.archive.gz"; run dump_mongo "$container" "$dumpfile" ;; + redis) dumpfile="$dumpfile.rdb"; run dump_redis "$container" "$dumpfile" ;; + esac + if [[ "$DRY_RUN" -eq 0 && ( ! -s "$dumpfile" ) ]]; then + warn "[$container] database dump looks empty, check credentials/tooling in the container" + fi +} + +# --------------------------------------------------------------------------- +# Volumes / bind mounts (live copy) +# --------------------------------------------------------------------------- + +backup_mounts() { + local container="$1" workdir="$2" + local mounts_json + mounts_json="$(docker inspect -f '{{json .Mounts}}' "$container")" + + [[ "$HAVE_JQ" -eq 1 ]] || { warn "[$container] jq missing, skipping volume/bind data copy"; return; } + + local count + count="$(echo "$mounts_json" | jq 'length')" + [[ "$count" -gt 0 ]] || return + + mkdir -p "$workdir/volumes" "$workdir/binds" + + local i + for ((i = 0; i < count; i++)); do + local type src name dest + type="$(echo "$mounts_json" | jq -r ".[$i].Type")" + src="$(echo "$mounts_json" | jq -r ".[$i].Source")" + name="$(echo "$mounts_json" | jq -r ".[$i].Name // empty")" + dest="$(echo "$mounts_json" | jq -r ".[$i].Destination")" + + if [[ "$type" == "volume" && -n "$name" ]]; then + log "[$container] copying named volume '$name' (live)" + local target="$workdir/volumes/$name" + mkdir -p "$target" + run docker run --rm \ + -v "${name}:/__src:ro" \ + -v "${target}:/__dst" \ + alpine:latest sh -c 'cp -a /__src/. /__dst/ 2>/dev/null || true' + elif [[ "$type" == "bind" ]]; then + local safe_name + safe_name="$(echo "$dest" | tr '/' '_' | sed 's/^_//')" + [[ -z "$safe_name" ]] && safe_name="root" + log "[$container] copying bind mount '$src' -> '$dest' (live)" + local target="$workdir/binds/$safe_name" + mkdir -p "$target" + if [[ -d "$src" ]]; then + run cp -a "$src/." "$target/" 2>/dev/null || warn "[$container] failed copying bind mount $src" + elif [[ -f "$src" ]]; then + run cp -a "$src" "$target/" + fi + fi + done +} + +# --------------------------------------------------------------------------- +# Recreate script (docker run equivalent), built from docker inspect +# --------------------------------------------------------------------------- + +generate_recreate_script() { + local container="$1" workdir="$2" + [[ "$HAVE_JQ" -eq 1 ]] || return + local info="$workdir/inspect.json" + local out="$workdir/recreate.sh" + + local image name restart network + image="$(jq -r '.[0].Config.Image' "$info")" + name="$(jq -r '.[0].Name' "$info" | sed 's#^/##')" + restart="$(jq -r '.[0].HostConfig.RestartPolicy.Name // "no"' "$info")" + network="$(jq -r '.[0].HostConfig.NetworkMode' "$info")" + + { + echo "#!/usr/bin/env bash" + echo "# Recreates container '$name' from image '$image'." + echo "# Review before running - adjust paths/volumes to match the restore location." + echo "set -euo pipefail" + printf 'docker run -d \\\n --name "%s" \\\n' "$name" + [[ "$restart" != "no" && -n "$restart" ]] && printf ' --restart "%s" \\\n' "$restart" + [[ -n "$network" && "$network" != "default" ]] && printf ' --network "%s" \\\n' "$network" + + jq -r '.[0].Config.Env[]? | @sh' "$info" | while read -r e; do + printf ' -e %s \\\n' "$e" + done + + jq -r '.[0].HostConfig.PortBindings // {} | to_entries[]? | .key as $cp | .value[]? | "\(.HostPort):\($cp)"' "$info" | while read -r p; do + printf ' -p %s \\\n' "$p" + done + + jq -r '.[0].Mounts[]? | select(.Type=="volume") | "\(.Name):\(.Destination)"' "$info" | while read -r v; do + printf ' -v %s \\\n' "$v" + done + jq -r '.[0].Mounts[]? | select(.Type=="bind") | "\(.Source):\(.Destination)"' "$info" | while read -r v; do + printf ' -v %s \\\n' "$v" + done + + printf ' "%s"\n' "$image" + } > "$out" + chmod +x "$out" +} + +# --------------------------------------------------------------------------- +# Per-container backup orchestration +# --------------------------------------------------------------------------- + +backup_container() { + local container="$1" + local mode db_type image was_running + + mode="$(get_label "$container" "docker-backup.mode")" + if [[ "$mode" == "skip" ]]; then + log "[$container] labeled docker-backup.mode=skip, skipping" + return + fi + + image="$(docker inspect -f '{{.Config.Image}}' "$container")" + db_type="$(detect_db_type "$image")" + was_running="$(docker inspect -f '{{.State.Running}}' "$container")" + + local workdir="$WORK_ROOT/$container" + mkdir -p "$workdir" + + docker inspect "$container" > "$workdir/inspect.json" + generate_recreate_script "$container" "$workdir" + + local stopped_by_us=0 + if [[ "$mode" == "stop" ]]; then + if [[ "$was_running" == "true" ]]; then + log "[$container] labeled docker-backup.mode=stop, stopping for consistent backup" + run docker stop "$container" >/dev/null + stopped_by_us=1 + fi + elif [[ -n "$db_type" && "$was_running" == "true" ]]; then + backup_database "$container" "$db_type" "$workdir" + elif [[ -n "$db_type" ]]; then + warn "[$container] database container is not running, cannot take a live dump; copying files as-is" + fi + + backup_mounts "$container" "$workdir" + + if [[ "$stopped_by_us" -eq 1 ]]; then + log "[$container] restarting container after backup" + run docker start "$container" >/dev/null + fi + + local archive="$OUTPUT_DIR/${container}_backup_${TIMESTAMP}.tar.bz2" + log "[$container] creating archive $archive" + run tar -cjf "$archive" -C "$WORK_ROOT" "$container" + rm -rf "$workdir" + + if [[ "$KEEP" -gt 0 ]]; then + apply_retention "$container" + fi +} + +apply_retention() { + local container="$1" + mapfile -t old < <(ls -1t "$OUTPUT_DIR/${container}_backup_"*.tar.bz2 2>/dev/null | tail -n +$((KEEP + 1))) + for f in "${old[@]:-}"; do + [[ -n "$f" ]] || continue + log "[$container] retention: removing old archive $f" + run rm -f "$f" + done +} + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- + +if [[ -n "$CONTAINERS" ]]; then + IFS=',' read -r -a TARGETS <<< "$CONTAINERS" +else + mapfile -t TARGETS < <(docker ps -a --format '{{.Names}}') +fi + +[[ ${#TARGETS[@]} -gt 0 ]] || die "no containers found to back up" + +FAILED=() +for c in "${TARGETS[@]}"; do + c="$(echo "$c" | xargs)" + [[ -z "$c" ]] && continue + if ! docker inspect "$c" >/dev/null 2>&1; then + warn "container '$c' not found, skipping" + continue + fi + if ! backup_container "$c"; then + err "backup failed for container '$c'" + FAILED+=("$c") + fi +done + +if [[ ${#FAILED[@]} -gt 0 ]]; then + err "completed with failures: ${FAILED[*]}" + exit 1 +fi + +log "all backups completed successfully, output: $OUTPUT_DIR" diff --git a/docker-restore.sh b/docker-restore.sh new file mode 100644 index 0000000..3f36391 --- /dev/null +++ b/docker-restore.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# +# docker-restore.sh - Restore a container from an archive created by docker-backup.sh +# +# Usage: +# ./docker-restore.sh [--start] +# +# What it does: +# 1. Extracts the archive to a temp dir +# 2. Restores named volumes / bind mount directories +# 3. Recreates the container via recreate.sh (if it was generated, requires jq at backup time) +# 4. If a database dump is present, restores it into the running container +# 5. With --start, starts the container after recreation (otherwise left stopped for review) +# +set -uo pipefail + +ARCHIVE="${1:-}" +START_AFTER=0 +[[ "${2:-}" == "--start" ]] && START_AFTER=1 + +[[ -n "$ARCHIVE" && -f "$ARCHIVE" ]] || { echo "Usage: $0 [--start]" >&2; exit 1; } +command -v docker >/dev/null 2>&1 || { echo "docker is required" >&2; exit 1; } + +log() { printf '[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*"; } + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/docker-restore.XXXXXX")" +trap 'rm -rf "$WORK"' EXIT + +tar -xjf "$ARCHIVE" -C "$WORK" +CONTAINER_DIR="$(find "$WORK" -mindepth 1 -maxdepth 1 -type d | head -n1)" +[[ -n "$CONTAINER_DIR" ]] || { echo "unexpected archive layout" >&2; exit 1; } +CONTAINER="$(basename "$CONTAINER_DIR")" + +log "restoring container '$CONTAINER' from $ARCHIVE" + +# Restore named volumes +if [[ -d "$CONTAINER_DIR/volumes" ]]; then + for voldir in "$CONTAINER_DIR/volumes"/*/; do + [[ -d "$voldir" ]] || continue + volname="$(basename "$voldir")" + log "recreating volume '$volname' and restoring its data" + docker volume inspect "$volname" >/dev/null 2>&1 || docker volume create "$volname" >/dev/null + docker run --rm -v "${volname}:/__dst" -v "${voldir}:/__src:ro" \ + alpine:latest sh -c 'cp -a /__src/. /__dst/' + done +fi + +# Restore bind mounts (print instructions, do not blindly overwrite host paths) +if [[ -d "$CONTAINER_DIR/binds" ]]; then + log "bind mount data extracted to: $CONTAINER_DIR/binds" + log "copy the relevant subfolders back to their original host paths manually (see inspect.json for original Source paths)" +fi + +# Recreate the container +if [[ -x "$CONTAINER_DIR/recreate.sh" ]]; then + log "recreating container via recreate.sh" + (cd "$CONTAINER_DIR" && ./recreate.sh) +else + log "no recreate.sh found, use $CONTAINER_DIR/inspect.json to recreate the container manually" +fi + +# Restore database dump, if present +if [[ -d "$CONTAINER_DIR/db" ]]; then + dumpfile="$(find "$CONTAINER_DIR/db" -type f | head -n1)" + if [[ -n "$dumpfile" ]]; then + log "found database dump: $dumpfile" + log "waiting for container '$CONTAINER' to accept connections before restoring (manual confirmation may be needed)" + case "$dumpfile" in + *.sql) + case "$dumpfile" in + *postgres*) log "run: docker exec -i $CONTAINER psql -U postgres < $dumpfile" ;; + *) log "run: docker exec -i $CONTAINER sh -c 'mysql -uroot -p\$MYSQL_ROOT_PASSWORD' < $dumpfile" ;; + esac + ;; + *.archive.gz) log "run: docker exec -i $CONTAINER mongorestore --archive --gzip < $dumpfile" ;; + *.rdb) log "stop the container, copy $dumpfile to its data dir as dump.rdb, then start it" ;; + esac + fi +fi + +if [[ "$START_AFTER" -eq 1 ]]; then + docker start "$CONTAINER" >/dev/null 2>&1 || true +fi + +log "restore steps completed. Review any manual steps printed above."