From a30a2f6a916fa41662942ebff137b096ed6f6f8b Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Sat, 5 Oct 2019 16:09:56 +0200 Subject: [PATCH] Initial version --- Dockerfile | 17 +++++++++++++++++ pgbackup.sh | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 Dockerfile create mode 100644 pgbackup.sh diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..e1c98cc --- /dev/null +++ b/Dockerfile @@ -0,0 +1,17 @@ +FROM alpine:latest as prefetch + +RUN set -ex \ + && apk --no-cache add \ + curl \ + && mkdir -p /src \ + && curl -sSfLo /src/dumb-init "https://github.com/Yelp/dumb-init/releases/download/v1.2.2/dumb-init_1.2.2_amd64" \ + && chmod 0755 /src/dumb-init + + +FROM postgres:9.6 + +COPY --from=prefetch /src/dumb-init /usr/local/bin/dumb-init +COPY pgbackup.sh /usr/local/bin/pgbackup.sh + +ENTRYPOINT ["/usr/local/bin/dumb-init"] +CMD ["/bin/bash", "/usr/local/bin/pgbackup.sh"] diff --git a/pgbackup.sh b/pgbackup.sh new file mode 100644 index 0000000..7c81cc8 --- /dev/null +++ b/pgbackup.sh @@ -0,0 +1,41 @@ +#!/bin/bash +set -euo pipefail + +if [[ -z ${PGPASSWORD:-} ]]; then + echo 'No $PGPASSWORD was present, aborting.' + exit 1 +fi + +set -x # Do NOT set earlier not to log the password + +# 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="${TARGET_DIR:-/var/lib/postgresql/data}" + +# Set defaults for PostgreSQL connect +PGHOST="${PGHOST:-postgres}" +PGUSER="${PGUSER:-postgres}" + +while [ 1 ]; do + + BACKUP_DATE=$(date +%Y-%m-%d_%H-%M-%S) + + pg_dumpall -h "${PGHOST}" -U "${PGUSER}" -g -f "${TARGET_DIR}/${BACKUP_DATE}_globals.sql" + gzip "${TARGET_DIR}/${BACKUP_DATE}_globals.sql" + + # Create backup + for dbname in $(psql -h "${PGHOST}" -U "${PGUSER}" -q -A -t -c "SELECT datname FROM pg_database" | grep -vE 'template[01]'); do + TARGET_FILE="${TARGET_DIR}/${BACKUP_DATE}_${dbname}.sql" + pg_dump -h "${PGHOST}" -U "${PGUSER}" -C "${dbname}" >"${TARGET_FILE}" + gzip "${TARGET_FILE}" + done + + # Cleanup old backups + find "${TARGET_DIR}" -mtime "${DELETE_OLDER_THAN}" \( -name '*.sql.gz' -or -name '*.sql' \) -delete + + # Sleep until next full hour + sleep $((3600 - $(date +%s) % 3600)) + +done