21/11/2026
Automated PostgreSQL Backup with Offsite Copy and Restore Test
Everyone says "we have backups." Then a disk dies, or someone runs a `DELETE` by mistake. You go to the backup and find it's empty, or three months old, or it lived on the same server that just died.
Everyone says "we have backups." Then a disk dies, or someone runs a DELETE by mistake. You go to the backup and find it's empty, or three months old, or it lived on the same server that just died.
A PostgreSQL backup has three parts. One: it runs automatically every night. Two: a copy goes somewhere else. Three: every so often you actually restore it to see that it works. On the ITcorv team we set up all three together on every database server. A backup you never tested isn't a backup.
This works on Debian 12 and Ubuntu 22.04/24.04 with PostgreSQL installed from packages. If your database runs in Docker, there's a separate section near the end. For the bigger DevOps picture, see our DevOps roadmap.
What is a PostgreSQL backup with pg_dump?
pg_dump takes a consistent copy of a database while it's running. Users can keep working; the dump reflects the moment it started.
We use the custom format (-Fc). It has a few advantages:
- It's compressed by default.
- With
pg_restoreyou can bring back a single table. - With
pg_restore --listyou can check whether the file is broken.
Keep one thing in mind: pg_dump does not back up users and roles. Those belong to the whole server. We dump them separately with pg_dumpall --globals-only.
1. The backup script
We run the script as the postgres user. That way it connects over the local socket and needs no password.
First, the directory:
sudo mkdir -p /var/backups/postgres
sudo chown postgres:postgres /var/backups/postgres
sudo chmod 700 /var/backups/postgresNow the file /usr/local/bin/pg-backup.sh:
#!/usr/bin/env bash
set -euo pipefail
BACKUP_DIR=/var/backups/postgres
DBS="appdb" # database names, space separated
KEEP_DAYS=7
STAMP=$(date +%F_%H%M)
for DB in $DBS; do
FILE="$BACKUP_DIR/${DB}_${STAMP}.dump"
pg_dump -Fc -f "$FILE" "$DB"
# if the file is broken, this fails and the script stops
pg_restore --list "$FILE" > /dev/null
done
# users and roles
pg_dumpall --globals-only > "$BACKUP_DIR/globals_${STAMP}.sql"
# delete backups older than KEEP_DAYS days
find "$BACKUP_DIR" -type f \( -name '*.dump' -o -name 'globals_*.sql' \) -mtime +"$KEEP_DAYS" -deleteMake it executable:
sudo chmod 755 /usr/local/bin/pg-backup.shset -euo pipefail means the script stops at the first failing line. Without it you could end up with a half-written file and think you have a backup.
2. Automate it with cron
The file /etc/cron.d/pg-backup:
# every night at 2:30 as the postgres user
30 2 * * * postgres /usr/local/bin/pg-backup.sh >> /var/log/pg-backup.log 2>&1Create the log so postgres can write to it:
sudo touch /var/log/pg-backup.log
sudo chown postgres:postgres /var/log/pg-backup.logIn /etc/cron.d the sixth column is the user name. Don't leave it out.
3. An offsite copy with rclone
A backup on the same server dies with that server. One copy has to go somewhere else: another server, or S3-compatible object storage.
We usually use rclone. It supports a lot of targets (S3, SFTP and many more).
sudo apt install rclone
sudo -u postgres rclone configIn rclone config, create a remote, say named offsite. Then add these two lines to the end of the script:
rclone copy "$BACKUP_DIR" offsite:pg-backups/$(hostname)
rclone delete --min-age 30d offsite:pg-backups/$(hostname)The first line copies new files. The second deletes backups older than 30 days on the remote side. So you keep 7 days on the server and a month offsite.
Storing data on a server you don't control? Encrypt it. rclone has a crypt remote type that encrypts before upload. Keep its password somewhere safe and separate, or the backup is useless.
4. Restore test (the most important part)
Take this seriously. Once a week, restore the latest backup into a separate database:
LATEST=$(sudo -u postgres sh -c 'ls -t /var/backups/postgres/appdb_*.dump | head -1')
sudo -u postgres createdb restore_test
sudo -u postgres pg_restore -d restore_test --no-owner --no-acl "$LATEST"Now count something you know should be there:
sudo -u postgres psql -d restore_test -c "SELECT count(*) FROM users;"Compare it with the production database. Close enough? Good. When you're done, drop it:
sudo -u postgres dropdb restore_testBetter yet, turn this test into a script and put it in cron weekly. If it fails, it should alert you.
Database in Docker
If PostgreSQL runs in a container (say it's named db):
docker exec db pg_dump -U postgres -Fc appdb > appdb_$(date +%F).dumpOne catch: don't add -t here (docker exec -t). With -t the output goes through a terminal and the binary file gets corrupted.
Restore:
docker exec -i db createdb -U postgres restore_test
docker exec -i db pg_restore -U postgres -d restore_test --no-owner < appdb_2026-11-14.dumpNot sure whether you need Docker Compose or Kubernetes? We covered that here.
Testing
After setting it up, check these:
1. Run the script once by hand:
sudo -u postgres /usr/local/bin/pg-backup.sh
sudo ls -lh /var/backups/postgres/You should see a .dump file and a globals_*.sql. The dump size shouldn't be zero.
2. Is the file healthy?
LATEST=$(sudo -u postgres sh -c 'ls -t /var/backups/postgres/appdb_*.dump | head -1')
sudo -u postgres pg_restore --list "$LATEST" | headIt should list tables and indexes, not an error.
3. Did the offsite copy arrive?
sudo -u postgres rclone ls offsite:pg-backups/$(hostname)4. Next morning, check the log:
tail /var/log/pg-backup.logNo errors, and tonight's file is in the directory? Then cron is working.
5. Run the restore test from section 4 once, end to end.
Tips
- The
pg_dumpversion must be the same as or newer than the server. An olderpg_dumpcan't back up a newer server. - Lock down the backup directory with
chmod 700. It holds all your customer data. - Keep
pg-backup.shin Git and roll it out from a pipeline, the same way as in our GitLab CI deploy guide. - Don't settle for "the script didn't error." Add an alert for when tonight's backup didn't show up. If you run Prometheus, you can monitor the age of the latest backup file too.
- Take a manual backup before any heavy change (migrations, version upgrades).
- Schedule the backup for low-traffic hours.
FAQ
Does pg_dump lock the server?
No. Normal reads and writes continue. But operations that change table structure (like ALTER TABLE) wait until the dump finishes, and while an ALTER waits, new queries on that table queue behind it. That's why we run it at night.
What if I need to go back to a specific minute?
pg_dump only has the moment the backup was taken. For restoring to any point in time (Point-in-Time Recovery), you need a base backup with pg_basebackup plus WAL archiving. Tools like pgBackRest make this easier. That's a separate post.
How often should I back up?
It depends on how much data you can afford to lose. A nightly backup means the worst case is a day of lost data. If that's too much, run it several times a day or move to PITR.
Should we do this by hand on many database servers?
No. Roll out the script and cron with Ansible or GitOps so every server is identical.
If you want help, the ITcorv team is here through consulting and DevOps services.