Automate PostgreSQL Backups on a VPS with a systemd Timer
Automate PostgreSQL backups on a VPS yourself: pg_dump in custom format, a systemd timer, pruning, a copy off the server, and a restore test you run.
On this page
- What a backup has to survive
- pg_dump, and why the custom format
- A pg_dump backup script
- Run it nightly with a systemd timer
- Delete old backups after N days
- Copy backups to S3 with rclone
- Test the backup with a restore
- What pg_dump does not cover
- How ox does the same job
- Key takeaways
- Frequently asked questions
- Next step
To automate PostgreSQL backups on a VPS, run pg_dump in custom format from a small script, start that script every night with a systemd timer, delete dumps past a set age, copy each new dump to S3-compatible storage off the server, and restore one into a scratch database now and then to prove it works. I tested the timer, bucket copy and restore on a fresh Ubuntu server with PostgreSQL from the Ubuntu archive.
I build ox, which takes these backups for the apps it deploys. Most of this post needs no ox at all, and the end says what ox does differently.
What a backup has to survive
Each of these asks for a different part of the setup.
A bad write, like a migration that drops the wrong column. Last night's dump on the same server covers this.
Losing the server, to a dead disk or a deleted VPS. Every copy on it goes too, so one copy has to live elsewhere.
A job that quietly stopped weeks ago while you believed you were covered. Failures have to show up somewhere you look.
A file that exists, has a sensible size, and still fails halfway through a restore.
pg_dump, and why the custom format
pg_dump exports one database while it keeps running. In the words of the pg_dump documentation, it "makes consistent exports even if the database is being used concurrently" and "does not block other users accessing the database (readers or writers)". The dump is a snapshot of the moment it started. The exceptions are operations that need an exclusive lock, such as most forms of ALTER TABLE, which wait for the dump to finish.
I use the custom format, --format=custom. It is compressed by default, and pg_restore can pull one table out of it or restore in parallel with -j. pg_restore --list also reads its table of contents without a database, a cheap first check for the script.
The same page names a limit you should know up front: "except in simple cases, pg_dump is generally not the right choice for taking regular backups of production databases." A nightly dump can lose up to a day of writes. For many small apps that is a fair trade. If losing an hour of orders would hurt, read what pg_dump does not cover first.
A pg_dump backup script
On Ubuntu, local connections to PostgreSQL use peer authentication by default, so a program running as the postgres system user connects as the postgres database superuser with no password. No password has to sit in a file, and pg_dump needs to read every table anyway.
#!/usr/bin/env bash
# /usr/local/bin/pg-backup: dump one database, check the file,
# delete old dumps, and copy new ones off the server.
set -euo pipefail
DB=myapp
DIR=/var/backups/postgres
KEEP_DAYS=14
REMOTE=offsite:my-backups/postgres
stamp=$(date -u +%Y-%m-%dT%H%M%SZ)
file="$DIR/$DB-$stamp.dump"
trap 'rm -f "$file.part"' EXIT
# Write under a temporary name, so a dump cut short never looks finished.
pg_dump --format=custom --file="$file.part" "$DB"
pg_restore --list "$file.part" > /dev/null
mv "$file.part" "$file"
# Delete local dumps older than KEEP_DAYS.
find "$DIR" -maxdepth 1 -type f -name "$DB-20??-??-??T??????Z.dump" -mtime +"$KEEP_DAYS" -delete
# Copy every dump the bucket does not have yet.
rclone --config /etc/pg-backup/rclone.conf copy "$DIR" "$REMOTE" --include "/$DB-20??-??-??T??????Z.dump"
set -euo pipefail makes the script stop at the first failed command and exit with an error, which is what lets systemd mark the run as failed. The dump is written to a .part file and renamed only after it passes the check, so a dump that died at 60% is never mistaken for a finished one, and the trap removes the partial file on the way out. UTC timestamps keep the names in order across clock changes.
Install it, and create a folder only postgres can read:
sudo apt install rclone
sudo install -d -o postgres -g postgres -m 700 /var/backups/postgres
sudo install -m 755 pg-backup /usr/local/bin/pg-backup
Run it nightly with a systemd timer
You could use cron. I use a systemd timer because the output of every run lands in the journal, a failed run leaves the service in a failed state you can list, and Persistent=true catches up on a run the server missed while it was off.
# /etc/systemd/system/pg-backup.service
[Unit]
Description=Back up the myapp PostgreSQL database
After=postgresql.service
[Service]
Type=oneshot
User=postgres
UMask=0077
Nice=10
IOSchedulingClass=idle
ExecStart=/usr/local/bin/pg-backup
# /etc/systemd/system/pg-backup.timer
[Unit]
Description=Run pg-backup.service every day
[Timer]
OnCalendar=*-*-* 03:30:00 UTC
Persistent=true
[Install]
WantedBy=timers.target
A timer starts the service with the same name, so pg-backup.timer runs pg-backup.service. Type=oneshot fits a job that runs and exits. After=postgresql.service makes a catch-up run at boot wait for the database. UMask=0077 makes each dump readable by postgres alone. Nice=10 and the idle I/O class lower the priority of pg_dump's own work, the compressing and the writing of the file. The reads happen inside PostgreSQL and are not slowed, so pick an hour when the app is quiet. Writing UTC in OnCalendar= keeps the time fixed whatever timezone the server is set to.
Delete old backups after N days
Without pruning, the dumps fill the disk and then the backup, and maybe the database, starts failing. The find line deletes dumps whose age is more than 14 full days. find drops the fraction of a day when it compares, so -mtime +14 keeps a dump that is 14.9 days old, and you end up with about 15 nightly dumps on disk. I checked this with files dated 14, 15 and 20 days back: only the last two went.
The pattern matches only names with this script's timestamp, so the dumps of a second database such as myapp-staging in the same folder are left alone.
Copy backups to S3 with rclone
A copy on the same server only protects you from your own mistakes. rclone is in Ubuntu's archive and speaks the S3 API, so it works with Amazon S3 and with the many stores that copy its API. Create a private working directory before entering credentials:
work=$(mktemp -d) && (umask 077 && touch "$work/rclone.conf")
Edit $work/rclone.conf with your editor. For an S3-compatible store with a custom endpoint, use:
# /etc/pg-backup/rclone.conf, owned by postgres, mode 600
[offsite]
type = s3
provider = Other
access_key_id = YOUR_KEY_ID
secret_access_key = YOUR_SECRET
endpoint = https://your-s3-endpoint
Install the file so that postgres alone can read it, since it holds a key to your bucket:
sudo install -d -o postgres -g postgres -m 700 /etc/pg-backup
sudo install -o postgres -g postgres -m 600 "$work/rclone.conf" /etc/pg-backup/rclone.conf && rm "$work/rclone.conf"
Give that key access to this one bucket only, and keep the bucket private, because the dumps in it are not encrypted.
rclone copy skips files the bucket already has, and it never deletes anything at the destination. I rely on the second part: if the local folder is emptied by mistake, the next run does not wipe the bucket to match. So the bucket needs its own rule for old files. On Amazon S3 that is a lifecycle rule with an expiration action, which deletes objects older than the age you set. Check what your provider offers, and keep more days there than on the server. If the rule is shorter than KEEP_DAYS, rclone uploads the expired dumps again every night. An age rule also keeps deleting after the job has stopped, so a job dead for longer than the rule leaves the bucket empty.
Turn it on, then run it once by hand rather than waiting for 03:30:
sudo systemctl daemon-reload
sudo systemctl enable --now pg-backup.timer
systemctl list-timers pg-backup.timer
sudo systemctl start pg-backup.service
journalctl -u pg-backup.service
When a run fails, the service shows up in systemctl --failed. If you want an email or a chat message instead, OnFailure= in the [Unit] section starts another unit whenever this one fails, and that unit can send the alert. A failed state covers only a run that started. A timer that was disabled leaves no trace, so check the date of the newest file in the bucket when you do the monthly restore.
Test the backup with a restore
A script that exits with 0 every night proves only that a file was written.
I cut a dump of a test database to 80% of its size and ran pg_restore --list on it, and it passed. A real restore of the same file failed with "could not read from input file: end of file". The check in the script catches an empty file or one that is not a dump at all. A file cut short or damaged after its table of contents passes it, and only a restore finds that.
Use only a trusted archive and trusted source database owners for a superuser restore. For any other archive, use an isolated disposable server without production credentials. Once a month, take the newest dump from the bucket, not from the server, and load it into a database you will throw away:
(
set -eu
tmp=$(sudo -u postgres mktemp -d)
trap 'sudo -u postgres rm -r -- "$tmp"' EXIT
db="restore_${tmp##*.}"
sudo -u postgres rclone --config /etc/pg-backup/rclone.conf copyto \
offsite:my-backups/postgres/myapp-2026-12-01T033000Z.dump "$tmp/restore-test.dump"
sudo -u postgres createdb -T template0 "$db"
trap 'sudo -u postgres dropdb "$db"; sudo -u postgres rm -r -- "$tmp"' EXIT
sudo -u postgres pg_restore --exit-on-error --dbname="$db" "$tmp/restore-test.dump"
sudo -u postgres psql -d "$db" -c 'SELECT count(*) FROM users;'
)
The test needs free disk for a second copy of the database, and the download goes into a folder only postgres can read. Creating the database from template0 gives you an empty one, as the pg_restore docs recommend. --exit-on-error matters, because by default pg_restore carries on past errors and only counts them at the end, which is easy to miss. Then check a table's row count looks right. If you restore on another machine that lacks your app's database user, add --no-owner --no-acl.
What pg_dump does not cover
Roles and other cluster-wide settings.
pg_dumpdumps one database and leaves out roles and tablespaces.pg_dumpall --globals-onlywrites those. Without it, a fresh server has none of your app's database users, and the owners and grants in the dump name users that do not exist. The script above does not save them. Run(umask 077; dir=$(mktemp -d) && sudo -u postgres pg_dumpall --globals-only > "$dir/globals.sql" && printf '%s\n' "$dir/globals.sql")after you add or change a database user, and keep the file with the dumps. It holds password hashes.Files your app keeps on disk, like user uploads. They are not in the database, so they are not in the dump. Copy that folder off the server the same way, with its own rclone line.
Writes since the last dump. To restore to any moment since the base backup, PostgreSQL has continuous archiving: a base backup taken with
pg_basebackupplus the write-ahead log saved as it is written. The continuous archiving chapter explains how. It has more moving parts, so add it when losing a day of writes would cost more than the extra setup.Restoring into an older PostgreSQL. A dump is expected to load into a newer major version, but there is no promise it loads into an older one.
How ox does the same job
ox takes the daily backup with nothing to turn on, and sends a copy off the server once you add your own S3 bucket in Settings. For PostgreSQL it runs pg_dump in custom format every day, soon after 03:00 UTC, and writes to a temporary name first, as the script above does with its .part file. It keeps 7 daily backups on the server, or 2 once your S3 bucket has a copy, and keeps 30 in the bucket. It also backs up each PostgreSQL database that has tables right before a deploy runs its migrate step, and keeps the last 3 of those on the server.
Where it goes further than the script: the copy sent to your bucket is encrypted with age, a restore loads the dump into a copy first so the live database changes only when the load works, and the database it replaced is kept under a new name until the next daily backup. Folders you list in ox.toml, such as uploads, are backed up too. The backups docs cover the details.
Where it does not: ox does not test your backups for you, and with daily backups a bad write can still lose up to a day. Restore one now and then as above. ox's own servers start the daily backup, so a day ox is down from 03:00 UTC to midnight gets none, where the timer above needs nothing outside your server. Your variables are in no backup, and ox keeps no copy of your backups on its own servers. What ox backs up, and how to leave lists where each copy lives.
Key takeaways
pg_dump --format=customtakes a consistent backup of a running database, compressed, and lets you restore single tables.- A systemd timer with
Persistent=truegives you a log for every run, a failed state you can list, and a catch-up run after downtime. - Write to a temporary name and rename on success, so a cut-short dump never looks finished.
- Keep at least one copy off the server, and let the bucket expire old files with its own rule.
pg_restore --listpassed on a truncated dump in my test. Only a real restore into a scratch database proves a backup works.
Frequently asked questions
Should I use pg_dump or pg_basebackup?
Use pg_dump for a small app where losing up to a day of writes is acceptable. It is one command, and its file also loads into a newer PostgreSQL. Use pg_basebackup with write-ahead log archiving when you need to restore to a moment between backups. It copies the whole cluster, and the archiving takes more setup to run well.
How often should I back up PostgreSQL?
Ask how much data you can afford to lose, because a dump only holds what existed when it started. Nightly suits most small apps. If a day of lost orders or signups would hurt, dump more often, or move to continuous archiving. Take an extra dump by hand before any risky migration, whatever the schedule.
Does pg_dump lock the database?
No. pg_dump reads a consistent snapshot while your app keeps reading and writing. It takes shared locks on the tables it dumps, and those block only operations that need an exclusive lock, such as most forms of ALTER TABLE, which wait until the dump ends. So avoid running migrations at backup time.
How do I restore a pg_dump backup?
Create an empty database with createdb -T template0, then run pg_restore --exit-on-error --dbname with that name and the dump file. Check a table you know before pointing the app at it. To pull back one table, add -t and the table name; it comes without its indexes. On a server without the dump's database users, add --no-owner --no-acl.
Next step
Set up the script and timer on a staging server, run it once with systemctl start, and then do the restore test before you trust it. If you would rather have ox run backups for your apps, the features page shows how they look, the quickstart takes you from a fresh server to a live app, and deploying Django without Docker shows a full app with PostgreSQL on the same kind of server.
New to running apps on your own server? How ox runs your apps shows what ox sets up on your server.
