On this page
- How do logical and physical PostgreSQL backups differ?
- How do you dump a database with pg_dump?
- How do you save roles and other global objects?
- How do you restore with pg_restore?
- How do you restore a single table or schema?
- How do you take a base backup with pg_basebackup?
- How do you set up point in time recovery?
- How do you automate and check PostgreSQL backups?
- Questions
How do logical and physical PostgreSQL backups differ?
A logical backup made with pg_dump stores the SQL needed to rebuild one database; a physical backup made with pg_basebackup copies the data files of the entire cluster. Choose logical for flexibility and physical for speed and point in time recovery.
- pg_dump: one database, consistent snapshot, restores into the same or a newer major version, lets you pick tables or schemas.
- pg_dumpall: every database plus the global objects (roles and tablespaces). Most useful with
--globals-onlynext to per-database dumps. - pg_basebackup: the whole cluster as it is on disk, restorable only into the same major version, combinable with archived WAL.
Paths and service names differ by distro. On Ubuntu and Debian the cluster lives in /var/lib/postgresql/16/main (the number is the major version) and the unit is postgresql@16-main. On Rocky and Alma the AppStream build uses /var/lib/pgsql/data and the unit postgresql, while the upstream PGDG packages use /var/lib/pgsql/16/data and postgresql-16. The PostgreSQL install guide covers which version each system ships.
How do you dump a database with pg_dump?
Run pg_dump as the postgres system user in custom format, which is compressed and lets pg_restore choose what to load.
sudo install -d -o postgres -g postgres -m 700 /var/backups/pg
sudo -u postgres pg_dump -Fc -f /var/backups/pg/shop-$(date +%F).dump shop
sudo -u postgres pg_restore -l /var/backups/pg/shop-2026-12-01.dump | headThe last command lists the contents, which is a quick sign that the file is complete. For big databases, the directory format dumps several tables in parallel:
sudo -u postgres pg_dump -Fd -j 4 -f /var/backups/pg/shop-$(date +%F).dir shopA plain SQL dump (-Fp, the default) is handy for reading or editing, but restores only through psql and cannot be filtered. Dumping from another machine works the same with -h db.example.net -U backup and a password in ~/.pgpass (mode 600) in the form host:port:database:user:password.
How do you save roles and other global objects?
Roles and tablespaces belong to the cluster, not to a database, so pg_dump skips them. Save them with pg_dumpall --globals-only next to every set of database dumps.
sudo -u postgres pg_dumpall --globals-only -f /var/backups/pg/globals-$(date +%F).sql
grep -c 'CREATE ROLE' /var/backups/pg/globals-2026-12-01.sqlThe file contains password hashes, so keep the same strict permissions as the dumps. To copy everything into a single SQL file, run pg_dumpall without options; it is simple but restores slowly and cannot be filtered. Role design is explained in PostgreSQL roles and permissions.
How do you restore with pg_restore?
Load the globals first, create an empty target database, then restore into it. Use several jobs to speed things up.
sudo -u postgres psql -f /var/backups/pg/globals-2026-12-01.sql
sudo -u postgres createdb -O shop shop_restore
sudo -u postgres pg_restore -d shop_restore -j 4 /var/backups/pg/shop-2026-12-01.dump
sudo -u postgres psql -d shop_restore -c 'SELECT count(*) FROM orders;'Errors about roles that already exist when loading globals are normal on the same server. To overwrite the live database, stop the application and use --clean --if-exists, which drops each object before recreating it:
sudo -u postgres pg_restore -d shop --clean --if-exists -j 4 /var/backups/pg/shop-2026-12-01.dumpWhen restoring on a server where the original owner role does not exist, add --no-owner --role=shop so everything is owned by the role you choose. A plain SQL dump restores with psql -d shop_restore -f shop.sql.
How do you restore a single table or schema?
Pass -t for a table or -n for a schema to pg_restore. Restore into a scratch database, check the rows, then copy what you need back.
sudo -u postgres createdb scratch
sudo -u postgres pg_restore -d scratch -t orders /var/backups/pg/shop-2026-12-01.dump
sudo -u postgres psql -d scratch -c '\d orders'For finer control, write the table of contents to a file, comment out the entries you do not want with a semicolon, and restore with that list:
sudo -u postgres pg_restore -l shop-2026-12-01.dump > toc.list
# edit toc.list, then
sudo -u postgres pg_restore -d scratch -L toc.list shop-2026-12-01.dumpMoving the recovered rows back can be as simple as INSERT INTO shop.orders SELECT through a foreign data wrapper, or a \copy out of one database and into the other.
How do you take a base backup with pg_basebackup?
Run pg_basebackup as postgres with WAL streaming so the copy is self-contained. Both Debian family and Enterprise Linux family packages allow local replication connections for postgres by default.
sudo -u postgres pg_basebackup -D /var/backups/pg/base-$(date +%F) -Ft -z -X stream -c fast -P
ls -lh /var/backups/pg/base-2026-12-01The result is base.tar.gz, pg_wal.tar.gz and a backup_manifest. On PostgreSQL 18, pg_verifybackup can check a tar format backup against that manifest directly; on older versions, verify a plain format copy (-Fp) instead or simply test the restore. To restore, stop the server, move the old data directory aside, unpack and start. Shown for Ubuntu 24.04 with version 16:
sudo systemctl stop postgresql@16-main
sudo mv /var/lib/postgresql/16/main /var/lib/postgresql/16/main.old
sudo install -d -o postgres -g postgres -m 700 /var/lib/postgresql/16/main
sudo -u postgres tar xzf /var/backups/pg/base-2026-12-01/base.tar.gz -C /var/lib/postgresql/16/main
sudo -u postgres tar xzf /var/backups/pg/base-2026-12-01/pg_wal.tar.gz -C /var/lib/postgresql/16/main/pg_wal
sudo systemctl start postgresql@16-mainOn Debian family systems the config files stay in /etc/postgresql/, so they are not part of the data directory; back them up separately. PostgreSQL 17 and newer can also take incremental base backups with --incremental once summarize_wal = on, merged later with pg_combinebackup.
How do you set up point in time recovery?
Archive every finished WAL segment to a safe directory, keep base backups, and on restore tell PostgreSQL where the archive is and when to stop. In postgresql.conf:
wal_level = replica
archive_mode = on
archive_command = 'test ! -f /var/backups/pg/wal/%f && cp %p /var/backups/pg/wal/%f'Create /var/backups/pg/wal owned by postgres and restart the server. Check that archiving runs with SELECT archived_count, failed_count FROM pg_stat_archiver;.
To recover, restore the newest base backup taken before the mistake as shown above, but before starting add these lines to postgresql.conf and create the signal file:
restore_command = 'cp /var/backups/pg/wal/%f %p'
recovery_target_time = '2026-12-01 14:29:00+00'
recovery_target_action = 'promote'sudo -u postgres touch /var/lib/postgresql/16/main/recovery.signal
sudo systemctl start postgresql@16-mainRemove the recovery settings once the server is back in normal operation. In production, copy the WAL archive to another machine as it is written, since a local archive dies with the disk.
How do you automate and check PostgreSQL backups?
Schedule a script as the postgres user, prune old files, copy the folder off the server and restore a dump into a scratch database every month.
sudo tee /usr/local/bin/pg-backup >/dev/null <<'EOF'
#!/bin/sh
set -eu
d=/var/backups/pg; day=$(date +%F)
pg_dumpall --globals-only -f "$d/globals-$day.sql"
for db in $(psql -Atc "SELECT datname FROM pg_database WHERE NOT datistemplate AND datname <> 'postgres'"); do
pg_dump -Fc -f "$d/$db-$day.dump" "$db"
done
find "$d" -maxdepth 1 -type f -mtime +14 -delete
EOF
sudo chmod 755 /usr/local/bin/pg-backup
sudo -u postgres /usr/local/bin/pg-backupRun it nightly from the postgres crontab (sudo crontab -u postgres -e) or a systemd timer; cron jobs shows both styles. Restic or rsync carries the files to another host, and the daily backups add-on adds a whole-disk copy. If a dump fails with a permission error, the target directory is not writable by postgres; if pg_basebackup is refused, check the replication lines in pg_hba.conf.
Questions about Back up and restore PostgreSQL
Can pg_dump run while the database is in use?
Yes. It reads one consistent snapshot and does not block normal reads and writes. Only schema changes such as ALTER TABLE wait until the dump finishes.
Can I restore a dump into a newer PostgreSQL version?
Yes, that is a common upgrade path. Use the pg_dump from the newer version against the old server for the best result.
Why does pg_restore say the file is not a valid archive?
The dump is plain SQL. Restore it with psql -f instead, or create custom format dumps with -Fc in future.
Does pg_dump include users and passwords?
No. Roles are global objects. Save them with pg_dumpall --globals-only next to each set of database dumps.
How long should I keep WAL archives?
At least back to the oldest base backup you would restore from. When you delete a base backup, delete the WAL files older than it as well.
More in Databases
- Install MySQL 8
- Install MariaDB
- Install PostgreSQL
- Install MongoDB
- PostgreSQL JSON, arrays and special types
- PostgreSQL views, triggers and CTEs
- PostgreSQL full-text search and encryption
- MySQL keys, indexes and full-text search
- MySQL JSON, views and stored procedures
- Apache Solr search server
- Install Redis or Valkey
- Install Memcached
- Apache Cassandra cluster
- Install Apache CouchDB
- InfluxDB for time series
- Install Elasticsearch
- Back up and restore MySQL and MariaDB
- MySQL users, roles and passwords
- PostgreSQL roles and permissions
- Repair a crashed MySQL table
- PostgreSQL streaming replication
- MongoDB replica set
- PostGIS for location data
- Database insight with PgHero
- Couchbase Server
- ArangoDB multi-model database
- Remote database access over SSH