Files
celtic-life-science/scripts/backup.sh
T
Shubhankar45 4e5e95775d --
2026-10-27 12:03:31 +00:00

28 lines
1.1 KiB
Bash
Executable File

#!/bin/sh
# Daily database backup, run by the `backup` service in docker-compose.yml.
#
# Takes a compressed pg_dump of the whole database once a day (and once straight away on
# start), keeps the last BACKUP_KEEP_DAYS days, and writes them to ./backups on the host so
# they can be copied off the server. Restore one with:
# gunzip -c backups/pharma-YYYYMMDD-HHMMSS.sql.gz | docker compose exec -T db psql -U pharma -d pharma
set -eu
KEEP_DAYS="${BACKUP_KEEP_DAYS:-14}"
INTERVAL="${BACKUP_INTERVAL_SECONDS:-86400}"
mkdir -p /backups
while true; do
stamp=$(date -u +%Y%m%d-%H%M%S)
target="/backups/${PGDATABASE}-${stamp}.sql.gz"
# Written under a temporary name, so a half-written file is never taken for a backup.
if pg_dump --clean --if-exists --no-owner | gzip > "${target}.part"; then
mv "${target}.part" "${target}"
echo "backup: wrote ${target} ($(du -h "${target}" | cut -f1))"
else
rm -f "${target}.part"
echo "backup: pg_dump FAILED at ${stamp}" >&2
fi
find /backups -name "${PGDATABASE}-*.sql.gz" -mtime "+${KEEP_DAYS}" -delete
sleep "${INTERVAL}"
done