first commit
This commit is contained in:
@@ -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: <output-dir>/<container>_backup_<timestamp>.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 <container> <VAR_NAME>
|
||||
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"
|
||||
Reference in New Issue
Block a user