Back up and restore
You make sure a recent copy of the database exists every night, you know how to make one by hand and to restore without making things worse. All the application’s state lives in PostgreSQL: reference data, solved schedule, plan versions, staff espace tokens, sessions. There is nothing else to back up, and nothing that can be rebuilt without the database.
If you encrypt the backups, the key is part of the backup. Lose
BACKUP_ENCRYPTION_KEYand every encrypted backup is lost with it, with no recourse: keep it in a vault, apart from the backups and off the machine (encrypt the backups).
Source: diagrammes/sauvegarde.puml (external site).
1. Let the nightly backup run
The application dumps the database by itself, every night at 4 am, as soon as BACKUP_DIR names a directory: a complete pg_dump --format=custom (schema and data, all editions), named planning-YYYYMMDD-HHMMSS.dump. Only the BACKUP_RETENTION most recent copies are kept; a dump dropped there by hand under another name is never touched by the rotation.
| Variable | Default | Effect |
|---|---|---|
BACKUP_DIR |
(empty) | Backup directory. Empty: nothing is scheduled, and Settings › Instance (behind “Advanced settings”) says so. The production compose sets it to /backup |
BACKUP_RETENTION |
10 |
Number of copies kept, between 1 and 30. Out of bounds, startup is refused: a retention trimmed silently is only discovered the day you look for the missing dump |
BACKUP_TIMEZONE |
Europe/Paris |
Time zone in which “4 am” is read and the file is named, independent of TZ |
BACKUP_CRON |
0 0 4 * * ? |
The schedule itself, if 4 am does not suit: six fields, seconds first (Quarkus syntax, 0 46 9 * * ? for 9:46 am), read in BACKUP_TIMEZONE |
BACKUP_ENCRYPTION_KEY |
(empty) | Encryption key of the dumps, dedicated (never INSTANCE_SECRET_KEY): 32 bytes in base64, openssl rand -base64 32. Set, every dump is encrypted before it reaches the disk; empty, it is written in clear and startup says so. Malformed, startup is refused |
A variable changed in
.env.prodis only read when the container is created:docker compose restartdoes not reread it, rundocker compose up -d --force-recreate app.
docker-compose.prod.yml also sets TZ (default Europe/Paris) on both containers. It does not enter the two nightly schedules, which each have their own zone, but decides the day boundary everywhere else: which timeslots are “already started” and so frozen during the event, when the availability collection and the swap fair open and close, the time on PDFs, the date of exported files. It must be the event’s: in UTC, everything would switch one to two hours after midnight, Paris time.
Prepare the directory
The directory must belong to uid 1000, the container’s user. docker-compose.prod.yml mounts ./backup there, next to the compose file: it is also the directory an external tool (borgmatic, restic…) copies off the machine. Create it before the first start, otherwise Docker creates it as root and the first backup fails with a write denial:
mkdir -p backup && sudo chown 1000:1000 backup
The directory survives the container, not the machine. A backup that never leaves the host protects against a wrong manipulation, not against losing the server: copy
./backupelsewhere, encrypted.
Encrypt the backups
A dump holds names, minors' birth dates and addresses: set BACKUP_ENCRYPTION_KEY in .env.prod (openssl rand -base64 32) and every dump is encrypted while it is written. No file in clear, even a temporary one, ever exists in BACKUP_DIR: the file is named planning-YYYYMMDD-HHMMSS.dump.enc. Settings › Instance says whether the copies are encrypted.
- The key belongs to the backups alone, distinct from
INSTANCE_SECRET_KEY: losing one does not cost you the other, and handing it to whoever restores does not open the instance’s secrets. Keep it off the machine and apart from the backups (a password vault): an encrypted copy whose key sits next to it protects nothing. - Without a key, nothing changes: dumps in clear, with a warning at startup. The rotation counts both suffixes, and a plain dump from before the switch lives beside the encrypted copies; a file dropped by hand under another name is never touched.
- Changing the key re-encrypts nothing: older copies stay readable with the older key, which
scripts/restaurer.shaccepts for a single command (see below). Keep the old key as long as a copy it protects is kept. - The encryption is authenticated: a wrong key, a truncated or altered file is refused whole, never half restored.
- It does not replace the off-machine copy: an encrypted
./backupthat stays on the host does not survive the host.
The format, to read it without the application
Chunked AES-256-GCM, streamed: a 16-byte header (PLBK, the version 0x01, the chunk size on 4 big-endian bytes, 7 random bytes), then chunks of size + 16 bytes (the last may be shorter). A chunk’s nonce is the 7 random bytes of the header, its index on 4 big-endian bytes and 0x01 if it is the last chunk, else 0x00; the authenticated data is the 16 header bytes. The index and the final byte make a truncated, reordered or extended file fail. With Python and the cryptography library:
# Decrypts a .dump.enc with nothing of the application (pip install cryptography).
# Usage: BACKUP_ENCRYPTION_KEY=<clé> python3 dechiffrer.py planning-….dump.enc planning.dump
import base64, os, struct, sys
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
aes = AESGCM(base64.b64decode(os.environ["BACKUP_ENCRYPTION_KEY"]))
f = open(sys.argv[1], "rb")
header = f.read(16)
assert header[:5] == b"PLBK\x01", "not an encrypted backup"
size = struct.unpack(">I", header[5:9])[0]
prefix = header[9:16]
block, i = f.read(size + 16), 0
out = open(sys.argv[2] + ".part", "wb")
while True:
following = f.read(size + 16)
last = not following
# A wrong key, a truncated or altered file raises InvalidTag: the partial output is deleted.
try:
out.write(aes.decrypt(prefix + struct.pack(">IB", i, last), block, header))
except BaseException:
out.close()
os.remove(sys.argv[2] + ".part")
raise
if last:
break
block, i = following, i + 1
out.close()
os.replace(sys.argv[2] + ".part", sys.argv[2])
Follow the backup status
Settings › Instance shows the folder, the retention, the next backup, the files present and the report of the last attempt, success or failure. A switch suspends it; only BACKUP_DIR turns it on.
A failed night warns the administration by e-mail: MAIL_ADMIN receives the date of the attempt, the reason, the date of the last successful backup and the number of consecutive failed nights. A second message goes out at the next success.
- Nothing goes out when the backup is suspended,
BACKUP_DIRis empty (a choice, not a failure) orMAIL_ADMINis empty (the application says so once at startup). If SMTP is down, the send failure is logged and nothing more. - If the database itself no longer answers, the message still goes out: the last success is read from the most recent dump in the directory (“unknown” if there is none), and the nights not recorded are counted as soon as the database answers again, as long as the application has not restarted.
- The exception also goes to error tracking when
SENTRY_DSNis set. An instance that no longer runs at all cannot alert itself: that is the job of the external probe.
If the backup fails on a write denial
-
Container moved from uid 1001 to 1000: the volume still belongs to the former user, and the report of Settings › Instance shows the denial. Take ownership once, stack stopped:
sudo chown -R 1000:1000 backup. An installation that used the named volumeplanning_backups(mounted on/backups) keeps its old dumps there: copy them once.docker run --rm -v planning_backups:/old -v "$PWD/backup":/new \ alpine sh -c 'cp -a /old/. /new/ && chown -R 1000:1000 /new' -
Directory
/backupsbecame/backup: a.env.prodthat still writesBACKUP_DIR=/backupskeeps working, the image making/backupsa link to/backup. Copy the old dumps as above and writeBACKUP_DIR=/backup, no hurry: the link is a compatibility.
2. Back up by hand
Before an update or a risky step, the “Back up now” button of Settings › Instance takes a copy at once, without touching the server. It only appears when BACKUP_DIR names a directory, it is reserved for the instance administrators and refused on a demo instance. The copy is written in the background: you can leave the screen, which says “in progress” and then the success or the reason for the failure. It has a name of its own, planning-manuel.dump (planning-manuel.dump.enc when BACKUP_ENCRYPTION_KEY is set: it is encrypted like the nightly ones, and no clear file exists even for an instant), which the nightly rotation neither counts nor removes; a new manual backup replaces the previous one, whatever its suffix, only the last one is kept. One backup is written at a time, the nightly one included: if the night falls during a manual backup, it waits for it for up to 30 minutes and then runs; past that delay, the night counts as a failed backup (shown, counted in the streak, alerted). Like the nightly copies, it is never downloadable: scripts/restaurer.sh lists it.
From the server, by hand:
docker compose -f docker-compose.prod.yml --env-file .env.prod exec -T postgres \
pg_dump -U festival -d festival --format=custom \
> "planning-$(date +%Y%m%d-%H%M).dump"
The service is called postgres, the database and its owner festival, fixed by docker-compose.prod.yml and not by .env.prod. Recommended rhythm: daily outside the event, hourly during it; the volume is small, what costs is the lost day of data entry.
A dump contains minors' personal data: names, birth dates, e-mail addresses, availabilities. Encrypt it at rest, keep it off the machine, never drop it on a demo instance or in a ticket.
3. Restore
Restoring is not a feature of the application, and that is deliberate: it is done on the PostgreSQL database, by you, on the host. Backing up is the nightly pg_dump; exchanging a data set is the YAML scenario.
The repository ships a guided script, scripts/restaurer.sh, to run from the directory of docker-compose.prod.yml (bash and docker compose, nothing else):
tmux new -s restauration # first: see the note below
scripts/restaurer.sh # lists the volume's dumps, asks which one
scripts/restaurer.sh planning-20260308-040000.dump # a named dump of the volume
scripts/restaurer.sh --fichier ./copie.dump # a file of the host
scripts/restaurer.sh --essai planning-20260308-040000.dump # the rehearsal, production untouched
Do the rehearsal once, cold: --essai restores into a temporary container of the image of the stack’s postgres service (same major as production), removed at the end, and shows the duration, the number of editions and the schema version. The script chains:
| Step | What it does |
|---|---|
| Decryption | a .dump.enc file (recognised by its header, not its name) is decrypted in full by the application image’s own program, with BACKUP_ENCRYPTION_KEY from .env.prod, before anything is stopped: a wrong key or a truncated or altered file stops there. An older key is given for that one command: BACKUP_ENCRYPTION_KEY=<older key> scripts/restaurer.sh planning-….dump.enc |
| Check | the file is read in full by pg_restore: a file that is not a --format=custom dump, or a truncated dump, is refused before anything is stopped. The dump’s schema version is compared with the image’s migrations: a newer dump is flagged and a confirmation asked (PLUS-RECENT, deemed given under --oui). An unreadable schema version (dump or image) is refused, --essai included, with nothing touched: check the dump and access to the image, or pass --sans-controle-version to restore without that check. The stack must be running, and the volume must have room for a safety dump |
| Safety | dump of the current state, planning-avant-restauration-YYYYMMDD-HHMMSS.dump (.dump.enc, encrypted with the same key, when BACKUP_ENCRYPTION_KEY is set), in the volume. The rotation ignores it: it never deletes itself, remove it once the restore is validated. Its name is displayed: it is the way back |
| Confirmation | the script says what will be overwritten (database festival, instance PUBLIC_URL) and asks you to type RESTAURER (--oui for a written procedure) |
| Restore | app stopped, database dropped then recreated, pg_restore in a single transaction that stops at the first error, app restarted. On failure or interruption (Ctrl-C, SSH cut): the safety dump is restored before the restart, so the application never restarts on an empty or half-restored database |
| Verification | waits for app to become healthy again (/q/health/ready), shows the length of the interruption |
Run the script in
tmux(orscreen, ornohup … > restauration.log 2>&1 &) over SSH: a session that drops does not leave the database half-restored, the script puts the safety dump back and restarts the application even without a terminal.
The database is recreated rather than cleaned (--clean), which only drops the objects present in the dump: restoring a dump older than the schema would leave the tables of later migrations, which Flyway would replay and fail. pg_restore and pg_dump come from the postgres container, hence the same major as the server; the backup volume is read by a throwaway container of the application image, so the script also works when the application no longer starts. The working copy is erased on exit; nothing leaves the host.
Restore a dump newer than the image
A dump newer than the deployed image (image rollback, dump from another instance) carries a schema ahead of the image’s migrations, and the application will refuse to start on it (rollbacks). The restore flags it before anything is stopped and asks for confirmation; the right move is almost always to deploy the image of the dump’s version first (APP_VERSION).
What a restore loses
Restoring during the event loses every write after the dump, hence the recommended hourly rhythm. An edition’s backups before a wipe (decision 0084 (external site)) come back as they were at the time of the pg_dump. Replaying an SQL export of the application (test tooling, no longer offered to the operator) erases them all, for every edition: the import deletes each edition before rewriting it, saving nothing first.
A mistake, an omission? Fix this page on GitHub. (external site)