Backups and point-in-time recovery for self-hosted Postgres with pgBackRest
Nightly dumps can only take you back to last night. pgBackRest gives Postgres full and incremental backups to S3 plus WAL archiving, so you can restore to the second before a bad DELETE. Here is the setup and a restore drill I ran on Postgres 18.
My blog's MySQL gets a nightly dump to S3 from a systemd timer, I wrote about it in Nightly MySQL and content backups to S3 with a systemd timer. That is fine for a blog. If I lose a day of posts, I can paste them back in. For a database that takes orders or payments it's not fine at all, because a nightly dump can only take you back to last night.
In this blog we will look at the Postgres version of that post, but one level up: pgBackRest with full and incremental backups to S3, WAL archiving, and a restore drill to an exact timestamp. Level is intermediate. You should be comfortable with Docker and psql, and know roughly what WAL is. I used Postgres 18.7 (the postgres:18 image) and pgBackRest 2.60.1, on a Mac with Docker.
Why WAL archiving and not just dumps
Postgres writes every change to the write-ahead log (WAL) before it touches the data files. If you keep a copy of the data files (a base backup) and every WAL segment written since, you can replay the log up to any point you like. That is point-in-time recovery, or PITR.
My blog server also takes daily EBS snapshots with Data Lifecycle Manager. Those are great for "the disk died". They're useless for "someone ran a DELETE at 14:05", because the nearest snapshot is from the night before and everything after it is gone.
pgBackRest does both halves. pgbackrest backup copies the data files, and pgbackrest archive-push, called by Postgres as its archive_command, ships every finished WAL segment to the repository. The repository can be a folder, S3, GCS or Azure.
A quick note on the project itself before you bet your data on it. In April 2026 the maintainer posted that pgBackRest was no longer being maintained. Two weeks later there was a maintenance update, and on 18 May a group of sponsors came in and he announced it will continue. Releases have been coming out since then, 2.60.1 landed on 16 November. I'm fine using it, but keep an eye on pgbackrest.org.
Postgres with pgBackRest in one image
pgBackRest has to run where the data directory is, because archive_command runs inside the Postgres server. So I add it to the official image itself. The image already has the PGDG apt repository, so it's one package.
FROM postgres:18
RUN apt-get update \
&& apt-get install -y --no-install-recommends pgbackrest ca-certificates \
&& rm -rf /var/lib/apt/lists/* \
&& mkdir -p /var/log/pgbackrest /var/lib/pgbackrest /var/spool/pgbackrest \
&& chown -R postgres:postgres /var/log/pgbackrest /var/lib/pgbackrest /var/spool/pgbackrest
docker build -t pg-pgbackrest:18 .
docker run --rm pg-pgbackrest:18 pgbackrest version
That printed pgBackRest 2.60.1.
One thing changed in the Postgres 18 image that matters here. The data directory moved to /var/lib/postgresql/18/docker and the volume is now /var/lib/postgresql. Older guides mount /var/lib/postgresql/data, which no longer is the data directory on 18. Check it with docker run --rm postgres:18 sh -c 'echo $PGDATA'.
The config
This is /etc/pgbackrest/pgbackrest.conf for a real server on EC2, writing to S3 in Mumbai.
[global]
repo1-type=s3
repo1-path=/pgbackrest
repo1-s3-bucket=my-pg-backups-111122223333
repo1-s3-endpoint=s3.ap-south-1.amazonaws.com
repo1-s3-region=ap-south-1
repo1-s3-key-type=auto
repo1-retention-full=2
repo1-cipher-type=aes-256-cbc
repo1-cipher-pass=change-me-to-a-long-random-string
compress-type=zst
process-max=2
start-fast=y
archive-async=y
spool-path=/var/spool/pgbackrest
log-level-console=info
log-level-file=detail
[main]
pg1-path=/var/lib/postgresql/18/docker
[main] is the stanza, pgBackRest's name for one Postgres cluster. repo1-s3-key-type=auto makes it take credentials from the instance role, so there are no keys in the file. repo1-retention-full=2 keeps two full backups and everything that depends on them, and it also expires WAL that is older than the oldest kept backup. The cipher encrypts the backups on the client side, before they reach S3. Lose that passphrase and the backups are useless, so it goes in a password manager, not only on the server.
archive-async=y lets archive-push hand segments off in the background and batch them, which matters once the database is busy.
About credentials from a container: with IMDSv2 and the default hop limit of 1, a process inside a Docker bridge network can't get a token from the instance metadata service. My Ghost host already has http_put_response_hop_limit = 2 in Terraform, which is what a container needs. If auto fails with a metadata error, check that first.
Turning on archiving
Postgres needs archive_mode and an archive_command. With Docker you can pass them as flags.
docker run -d --name pg -e POSTGRES_PASSWORD=secret \
-v pgdata:/var/lib/postgresql \
-v "$PWD/pgbackrest.conf:/etc/pgbackrest/pgbackrest.conf:ro" \
pg-pgbackrest:18 \
-c archive_mode=on \
-c "archive_command=pgbackrest --stanza=main archive-push %p" \
-c archive_timeout=60
archive_timeout=60 forces a WAL switch at least once a minute when there is any activity, so on a quiet database you lose at most about a minute even if the server dies. Without it a half-full 16 MB segment can sit there for hours.
Then create the stanza and check it.
docker exec -u postgres pg pgbackrest --stanza=main stanza-create
docker exec -u postgres pg pgbackrest --stanza=main check
My first check sat there for a full minute before it printed successfully archived. I think this is basically because Postgres had already tried to archive a segment before the stanza existed, those attempts failed, and the archiver backs off for 60 seconds after a few failures. Every check after that took well under a second. So create the stanza right after you turn archiving on, and don't panic about the first run.
Testing it without a real bucket
I didn't want to touch a real AWS account for this, so for the drill I pointed pgBackRest at a local S3 server. My first try was MinIO and docker pull minio/minio came back with "pull access denied". Looks like the community image is gone from Docker Hub. I used versitygw instead, a small S3 gateway in Go. pgBackRest only talks HTTPS to S3, so it needs a certificate, even a self-signed one.
openssl req -x509 -newkey rsa:2048 -nodes -days 7 -subj /CN=s3local -keyout s3.key -out s3.crt
docker network create pgbr
docker volume create s3data
docker run --rm -v s3data:/data --entrypoint sh postgres:18 -c 'mkdir -p /data/root/my-pg-backups /data/meta'
docker run -d --name s3 --network pgbr --network-alias s3local \
-v s3data:/data -v "$PWD/s3.crt:/certs/s3.crt:ro" -v "$PWD/s3.key:/certs/s3.key:ro" \
versity/versitygw:latest --access localkey --secret localsecret12345 \
--cert /certs/s3.crt --key /certs/s3.key posix --sidecar /data/meta /data/root
The first time I put the metadata folder inside the gateway root and it refused to start with sidecar directory cannot be inside the gateway root directory. Hence /data/root and /data/meta.
For the local copy of the config only the repo lines change. The Postgres container also joins the pgbr network.
repo1-s3-bucket=my-pg-backups
repo1-s3-endpoint=s3local
repo1-s3-region=us-east-1
repo1-s3-uri-style=path
repo1-storage-port=7070
repo1-storage-verify-tls=n
repo1-s3-key=localkey
repo1-s3-key-secret=localsecret12345
Never use repo1-storage-verify-tls=n against real S3.
Full and incremental backups
Let us make some data and back it up. A full first, then an incremental, which only copies files changed since the last backup.
pg() { docker exec -u postgres pg psql -X -q -At -c "$1"; }
br() { docker exec -u postgres pg pgbackrest --stanza=main "$@"; }
pg "CREATE TABLE orders (id bigint generated always as identity primary key, item text, created_at timestamptz default now())"
pg "INSERT INTO orders (item) SELECT 'item-' || g FROM generate_series(1, 1000) g"
br --type=full backup
pg "INSERT INTO orders (item) SELECT 'late-' || g FROM generate_series(1, 500) g"
br --type=incr backup
br info shows what is in the repository. This is trimmed from my run.
stanza: main
status: ok
cipher: aes-256-cbc
db (current)
wal archive min/max (18): 000000010000000000000001/000000010000000000000008
full backup: 20261119-063729F
database size: 23MB, database backup size: 23MB
repo1: backup set size: 2.7MB, backup size: 2.7MB
incr backup: 20261119-063729F_20261119-063731I
database size: 23MB, database backup size: 160.3KB
repo1: backup set size: 2.8MB, backup size: 18.6KB
backup reference total: 1 full
23 MB of database became 2.7 MB in the bucket with zstd, and the incremental was 18.6 KB. An empty Postgres cluster is mostly the same system catalogues, so it compresses really well, a real database won't shrink that much.
The accident and the restore drill
Now the bad day. I insert one more row, note the time, and then delete everything.
pg "INSERT INTO orders (item) VALUES ('the last good order')"
TARGET=$(pg "SELECT now()")
pg "DELETE FROM orders"
pg "SELECT pg_switch_wal()"
In real life you won't have $TARGET handy. You'll get it from the application logs or the slow query log (I covered that in Finding slow queries with pg_stat_statements and auto_explain), roughly "the delete happened around 14:05, restore to 14:04". pg_switch_wal() is only there so the WAL with the delete gets archived right away in the test.
I restore into fresh volume and a separate container, the same way I test the MySQL restore on a scratch stack. The live database stays untouched while you look around.
docker volume create restoredata
docker run --rm --network pgbr -u postgres -v restoredata:/var/lib/postgresql \
-v "$PWD/pgbackrest.conf:/etc/pgbackrest/pgbackrest.conf:ro" \
pg-pgbackrest:18 pgbackrest --stanza=main --type=time "--target=$TARGET" \
--target-action=promote --archive-mode=off restore
docker run -d --name pg-restore --network pgbr -e POSTGRES_PASSWORD=secret \
-v restoredata:/var/lib/postgresql \
-v "$PWD/pgbackrest.conf:/etc/pgbackrest/pgbackrest.conf:ro" \
pg-pgbackrest:18
--archive-mode=off actually matters. Without it the restored copy would start archiving its own WAL into the same repository as production, after promotion it is on a new timeline, so it won't overwrite anything, but it's clutter you don't want from a drill.
pgBackRest picked the incremental backup on its own, restore backup set 20261119-063729F_20261119-063731I, recovery will start at 2026-11-19 06:37:31. Then the Postgres log of the restored container told the story.
LOG: starting point-in-time recovery to 2026-11-19 06:37:33.501129+00
LOG: recovery stopping before commit of transaction 757, time 2026-11-19 06:37:34.562992+00
LOG: selected new timeline ID: 2
LOG: archive recovery complete
Transaction 757 was my DELETE. And the table:
docker exec pg-restore psql -U postgres -At -c \
"SELECT count(*), max(id), (SELECT item FROM orders ORDER BY id DESC LIMIT 1) FROM orders"
1501|1501|the last good order
All 1,501 rows, including the one inserted a second before the delete. The restore printed one warning, unknown group 'root' in backup manifest mapped to current group, which comes from a folder in the Docker volume owned by root. Harmless here.
From here you either copy the lost rows back into production with pg_dump -t orders or, if the damage is wide, point the app at the restored server.
Scheduling it
Same pattern as my MySQL backups: a systemd timer on the host that runs the command inside the container. A full backup on Sunday and incrementals the other nights.
# /etc/systemd/system/pg-backup@.service
[Unit]
Description=pgBackRest %i backup
After=docker.service
[Service]
Type=oneshot
ExecStart=/usr/bin/docker exec -u postgres pg pgbackrest --stanza=main --type=%i backup
# /etc/systemd/system/pg-backup-full.timer
[Timer]
Unit=pg-backup@full.service
OnCalendar=Sun *-*-* 20:00:00 UTC
Persistent=true
[Install]
WantedBy=timers.target
The incremental timer is the same with Unit=pg-backup@incr.service and OnCalendar=Mon..Sat *-*-* 20:00:00 UTC.
The instance role needs a bit more than my MySQL backup did. pgBackRest expires old backups and WAL itself, so it needs s3:DeleteObject, which I deliberately left out for the MySQL script. To keep some protection anyway, turn on bucket versioning with a short noncurrent_version_expiration, so a deleted backup can still be recovered for a few days.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::my-pg-backups-111122223333"
},
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": "arn:aws:s3:::my-pg-backups-111122223333/pgbackrest/*"
}
]
}
Finally, put the drill itself on the calendar. Once a month, restore last night's backup to a time you pick, count some rows and throw the container away. The whole thing took under a minute on my laptop with a tiny database, and a real one mostly costs download time.