Skip to content

Instantly share code, notes, and snippets.

@ismdeep
Created March 1, 2024 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ismdeep/34eda2fac762f2fdcabc3f6de2df7884 to your computer and use it in GitHub Desktop.
Save ismdeep/34eda2fac762f2fdcabc3f6de2df7884 to your computer and use it in GitHub Desktop.
Backup Docker Compose Directory
#!/usr/bin/env bash
set -e
help() {
echo 'Usage: backup-docker-compose -t <tag_name> [docker-compose-working-directory]'
echo ''
echo ' e.g. $ backup-docker-compose -t v1.3.3-1 /data/deploy/nginx'
echo ' $ backup-docker-compose -t v1.3.3-1'
echo ' $ backup-docker-compose'
}
# archive tag
archive_tag=""
while getopts ":t:" opt; do
case ${opt} in
t )
archive_tag="${OPTARG}"
;;
* )
;;
esac
done
shift $((OPTIND -1))
if [ "${archive_tag}" == "" ]; then
archive_tag="$(date +%y%m%d%H%M%S-%N)"
fi
# get docker-compose working directory
other_args=("$@")
first_arg="${other_args[0]}"
workdir="$(realpath "${first_arg:-"$(pwd)"}")"
echo "==> archive: ${workdir} ${archive_tag}"
cluster_name="$(basename "${workdir}")"
archived_file_name="${cluster_name}-${archive_tag}.tar.xz"
# 1. check /usr/bin/docker-compose
if [ ! -f /usr/bin/docker-compose ]; then
echo "[ERROR] file not found: /usr/bin/docker-compose"
exit 1
fi
# 2. check docker-compose.yaml
if [ ! -f "${workdir:?}/docker-compose.yaml" ]; then
echo "[ERROR] file not found: ${workdir:?}/docker-compose.yaml"
exit 1
fi
# 3. check already exists
if [ -f "$(realpath "$(dirname "${workdir}")")/${archived_file_name}" ]; then
echo "[ERROR] already exists: $(realpath "$(dirname "${workdir}")")/${archived_file_name}"
exit 1
fi
# get running cnt
running_cnt="$({
cd "${workdir}"
docker-compose ps -q | wc -l
})"
# stop services if is running
if [ "${running_cnt:-0}" != 0 ]; then
docker-compose --project-directory "${workdir}" --progress quiet down && echo "OK: stop services"
fi
# backup
(
cd "$(realpath "$(dirname "${workdir}")")"
tar cf - "${cluster_name}/" | pv -s "$(du -sb "${cluster_name}/" | awk '{print $1}')" | xz -T 0 > "${archived_file_name}"
)
echo "OK: backup at $(realpath "$(dirname "${workdir}")")/${archived_file_name}"
# start services if is running
if [ "${running_cnt:-0}" != 0 ]; then
docker-compose --project-directory "${workdir}" --progress quiet up -d && echo "OK: resume services"
fi
echo "================================ FINISHED: $(date +%Y-%m-%d-%H%M%S) ================================"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment