diff --git a/compose.yml b/compose.yml index c8656ea..7102b2f 100644 --- a/compose.yml +++ b/compose.yml @@ -98,6 +98,10 @@ services: db: image: postgres:17 + configs: + - source: pg_backup + target: /pg_backup.sh + mode: 0555 healthcheck: test: [ "CMD", "pg_isready", "-q", "-d", "postgres", "-U", "liberaforms" ] timeout: 45s @@ -107,6 +111,11 @@ services: POSTGRES_USER: liberaforms POSTGRES_DB: liberaforms POSTGRES_PASSWORD_FILE: /run/secrets/db_password + deploy: + labels: + backupbot.backup.pre-hook: "/pg_backup.sh backup" + backupbot.backup.volumes.postgres.path: "backup.sql" + backupbot.restore.post-hook: '/pg_backup.sh restore' volumes: - db:/var/lib/postgresql/data secrets: @@ -145,3 +154,6 @@ configs: nginx_conf: name: ${STACK_NAME}_nginx_conf_${NGINX_CONFIG_VERSION} file: nginx.conf + pg_backup: + name: ${STACK_NAME}_pg_backup_${PG_BACKUP_VERSION} + file: pg_backup.sh \ No newline at end of file diff --git a/pg_backup.sh b/pg_backup.sh new file mode 100644 index 0000000..e83074d --- /dev/null +++ b/pg_backup.sh @@ -0,0 +1,34 @@ +#!/bin/bash + +set -e + +BACKUP_FILE='/var/lib/postgresql/data/backup.sql' + +function backup { + export PGPASSWORD=$(cat /run/secrets/db_password) + pg_dump -U ${POSTGRES_USER} ${POSTGRES_DB} > $BACKUP_FILE +} + +function restore { + cd /var/lib/postgresql/data/ + restore_config(){ + # Restore allowed connections + cat pg_hba.conf.bak > pg_hba.conf + su postgres -c 'pg_ctl reload' + } + # Don't allow any other connections than local + cp pg_hba.conf pg_hba.conf.bak + echo "local all all trust" > pg_hba.conf + su postgres -c 'pg_ctl reload' + trap restore_config EXIT INT TERM + + # Recreate Database + psql -U ${POSTGRES_USER} -d postgres -c "DROP DATABASE ${POSTGRES_DB} WITH (FORCE);" + createdb -U ${POSTGRES_USER} ${POSTGRES_DB} + psql -U ${POSTGRES_USER} -d ${POSTGRES_DB} -1 -f $BACKUP_FILE + + trap - EXIT INT TERM + restore_config +} + +$@