From 427e25f8112dd9e09b47fcabb345098a3c54562c Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Tue, 20 Mar 2018 12:28:35 +0100 Subject: [PATCH] Initial version Signed-off-by: Knut Ahlers --- Dockerfile | 14 ++++++++++++++ backup.sh | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 Dockerfile create mode 100755 backup.sh diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..f4dae20 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,14 @@ +FROM mariadb:10.2 + +RUN set -ex \ + && apt-get update \ + && apt-get install -y --no-install-recommends percona-toolkit \ + && apt-get clean -y \ + && rm -rf /var/lib/apt/lists/* + +COPY backup.sh /usr/local/bin/ + +VOLUME ["/data"] + +ENTRYPOINT ["/bin/bash"] +CMD ["/usr/local/bin/backup.sh"] diff --git a/backup.sh b/backup.sh new file mode 100755 index 0000000..1b136be --- /dev/null +++ b/backup.sh @@ -0,0 +1,52 @@ +#!/bin/bash +set -euo pipefail + +function step() { + echo "[$(date +%Y-%m-%d %H:%M:%S)] $@" +} + +[ -z "${MYSQL_PASSWORD:-}" ] && { + echo 'No $MYSQL_PASSWORD was set, aborting.' + exit 1 +} + +while [ 1 ]; do + + # Remove old backups older than N days (default 2d) + DELETE_OLDER_THAN=${DELETE_OLDER_THAN:-2} + + # This directory is exposed by the postgres image + TARGET_DIR=/var/lib/postgresql/data + + BACKUP_DATE=$(date +%Y-%m-%d_%H-%M-%S) + + # Collect databases + step "Starting backup..." + DATABASES=$(mysql \ + -h "${MYSQL_HOST:-mariadb}" -u "${MYSQL_USER:-root}" -p${MYSQL_PASSWORD} \ + -B --disable-column-names -e 'SHOW DATABASES' | + grep -vE '(information_schema|performance_schema|mysql|tmp)') + + # Create backup + for db_name in ${DATABASES}; do + TARGET_FILE="${TARGET_DIR}/${BACKUP_DATE}_${dbname}.sql" + step "Creating backup of ${db_name} in ${TARGET_FILE}..." + mysqldump \ + -h "${MYSQL_HOST:-mariadb}" -u "${MYSQL_USER:-root}" -p${MYSQL_PASSWORD} \ + -a --database "${db_name}" | gzip >"${TARGET_FILE}" + done + + # Dump grants + GRANTS_FILE="${TARGET_DIR}/${BACKUP_DATE}_grants.sql" + step "Creating grants backuo in ${GRANTS_FILE}..." + pt-show-grants -h "${MYSQL_HOST:-mariadb}" -u "${MYSQL_USER:-root}" -p "${MYSQL_PASSWORD}" >"${GRANTS_FILE}" + + # Cleanup old backups + step "Removing old backups..." + find "${TARGET_DIR}" -name '*.sql.gz' -mtime "${DELETE_OLDER_THAN}" -delete + + # Sleep until next full hour + step "I'm done, see ya next hour!" + sleep $((3600 - $(date +%s) % 3600)) + +done