Backup & Restore
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A backup is only useful if you have restored from it. PostgreSQL supports two families of backups: logical (SQL or
archive files describing the data) and physical (a copy of the data directory plus the write-ahead log). This page
runs both on PostgreSQL 18.6 (postgres:latest, container pg-b), including a complete point-in-time recovery. The
shop schema is the one from Getting Started. Long listings are
trimmed where stated. For a general overview of moving data between systems see
Database Migration.
Logical backups with pg_dump
pg_dump connects as an ordinary client, takes a consistent snapshot using MVCC, and writes the definition and data
of one database without blocking readers or writers. It can write four formats:
| Flag | Format | Notes |
|---|---|---|
|
Plain SQL script |
Restore with |
|
Custom archive |
Compressed; restore with |
|
Directory |
One file per table; the only format that supports parallel dump ( |
|
Tar |
Uncompressed archive; limited compared to custom |
pg_dump -U postgres -d postgres -n shop -f shop.sql # plain SQL
pg_dump -U postgres -Fc -n shop -f shop.dump postgres # custom
pg_dump -U postgres -Fd -j 2 -n shop -f shop_dir postgres # directory, 2 parallel jobs
pg_dump -U postgres -Ft -n shop -f shop.tar postgres # tar
-rw-r--r-- 1 postgres postgres 7553 shop.dump drwx------ 2 postgres postgres 4096 shop_dir -rw-r--r-- 1 postgres postgres 6052 shop.sql -rw-r--r-- 1 postgres postgres 19456 shop.tar
The plain script starts with session settings and then CREATE SCHEMA shop; followed by the tables and COPY
data. (Recent minor releases also write a \restrict line near the top, a protection against malicious dump files when
restoring with psql.) The directory format holds one compressed file per table plus a table of contents:
3482.dat.gz 3483.dat.gz 3484.dat.gz 3485.dat.gz toc.dat
Useful filters are -n schema, -t table, -T table to exclude, --schema-only (-s), --data-only (-a) and
--column-inserts, which writes one portable INSERT per row:
pg_dump -U postgres -d postgres -t shop.products --data-only --column-inserts | grep INSERT | head -2
INSERT INTO shop.products (sku, name, category, price, stock, tags, attrs) VALUES ('A-1', 'Standing Desk', 'furniture', 349.00, 12, '{office,ergonomic}', '{"color": "oak", "width_cm": 160, "adjustable": true}');
INSERT INTO shop.products (sku, name, category, price, stock, tags, attrs) VALUES ('A-2', 'Office Chair', 'furniture', 189.50, 30, '{office,ergonomic,sale}', '{"mesh": true, "color": "black"}');
Roles and globals: pg_dumpall
pg_dump covers one database only; roles and tablespaces are cluster-wide. pg_dumpall --globals-only dumps them,
including the password verifiers (so guard the file like a secret):
pg_dumpall -U postgres --globals-only | grep -E "^(CREATE|ALTER) ROLE" | head -4
CREATE ROLE alice; ALTER ROLE alice WITH NOSUPERUSER INHERIT NOCREATEROLE NOCREATEDB LOGIN NOREPLICATION NOBYPASSRLS PASSWORD 'SCRAM-SHA-256$...'; CREATE ROLE app_read; ALTER ROLE app_read WITH NOSUPERUSER INHERIT NOCREATEROLE NOCREATEDB NOLOGIN NOREPLICATION NOBYPASSRLS;
(The password hash is shortened here.) A common routine is pg_dumpall --globals-only for roles plus one pg_dump -Fc
per database. Plain pg_dumpall without options writes everything as one SQL script, but it cannot be restored
selectively or in parallel.
Restoring with pg_restore
pg_restore -l prints the table of contents of a custom or directory archive; the list can be edited and fed back with
-L to restore a chosen subset in a chosen order:
pg_restore -l shop.dump | head -22
; Archive created at 2026-11-10 19:08:02 UTC ; dbname: postgres ; Compression: gzip ; Format: CUSTOM ; Dumped from database version: 18.6 (Debian 18.6-1.pgdg13+2) ; Selected TOC Entries: 8; 2615 16981 SCHEMA - shop postgres 223; 1259 16982 TABLE shop customers postgres 226; 1259 17033 TABLE shop order_items postgres 225; 1259 17016 TABLE shop orders postgres 224; 1259 16998 TABLE shop products postgres 3482; 0 16982 TABLE DATA shop customers postgres ...
(Trimmed.) Selective restore of one table. -t restores that object only (not its dependencies), so the target schema
must exist:
createdb -U postgres restored1
psql -U postgres -d restored1 -qc "CREATE SCHEMA shop"
pg_restore -U postgres -d restored1 --no-owner -n shop -t customers shop.dump
psql -U postgres -d restored1 -c "\dt shop.*" -c "select count(*) from shop.customers"
Schema | Name | Type | Owner
--------+-----------+-------+----------
shop | customers | table | postgres
count
-------
4
Without that CREATE SCHEMA, the same command prints ERROR: schema "shop" does not exist twice and restores
nothing. Parallel restore works on custom and directory archives with -j; indexes and constraints are built
concurrently, which is where most restore time goes:
createdb -U postgres restored2
pg_restore -U postgres -d restored2 -j 2 --no-owner shop_dir
psql -U postgres -d restored2 -Atc "select count(*) from shop.order_items"
11
Other options worth knowing: --section=pre-data|data|post-data to split a restore, -s for schema only, --clean --if-exists to drop objects first, --single-transaction to make a restore all-or-nothing (incompatible with -j),
and -e to stop at the first error. After restoring, run ANALYZE: dumps carry no planner statistics (see
Administration).
Logical backups are portable across major versions and operating systems and are the standard way to upgrade
(pg_dump from the old server, pg_restore into the new one), but a restore must replay every insert and rebuild every
index, so recovery time grows with data size, and a dump captures only one moment in time.
Physical backups with pg_basebackup
A physical backup copies the data directory itself. pg_basebackup does this over the replication protocol while the
server runs, and with -X stream it also streams the WAL generated during the backup so the copy is self-contained.
pg_basebackup -U postgres -D /backup/base -Fp -X stream -c fast -P -v
pg_basebackup: created temporary replication slot "pg_basebackup_69" 24524/24524 kB (100%), 1/1 tablespace pg_basebackup: write-ahead log end point: 0/B000120 pg_basebackup: syncing data to disk ... pg_basebackup: renaming backup_manifest.tmp to backup_manifest pg_basebackup: base backup completed
(Trimmed.) The role must have the REPLICATION attribute (or be a superuser) and pg_hba.conf must permit a
replication connection; the Docker image allows both for the local socket. The result is a complete cluster plus a
backup_label identifying the start point and a backup_manifest listing every file with its checksum:
START WAL LOCATION: 0/B000028 (file 00000001000000000000000B) CHECKPOINT LOCATION: 0/B000080 BACKUP METHOD: streamed BACKUP FROM: primary START TIME: 2026-11-10 19:08:34 UTC LABEL: pg_basebackup base backup START TIMELINE: 1
Use -Ft -z for compressed tar files (3.3 MB here versus 40 MB uncompressed), -R to write replication settings for a
standby (see Replication & High Availability), and --checkpoint=fast
to avoid waiting for the next scheduled checkpoint.
Verifying a backup
pg_verifybackup checks a plain-format base backup against its manifest (file presence, sizes, checksums) and parses the
WAL that the backup needs:
pg_verifybackup /backup/base
backup successfully verified
Appending a byte to one file in a copy of the backup is detected immediately:
pg_verifybackup: error: "base/1/PG_VERSION" has size 5 on disk but size 3 in the manifest
For a tar-format backup, unpack it first (or pass -n to skip WAL parsing). Verification proves the files are intact; it
does not prove the backup restores, which is why the next section ends with a real restore.
Continuous archiving and point-in-time recovery
A base backup restores the database to the moment the backup finished. To recover to any later point, the server must also archive every completed WAL segment, and recovery replays them on top of the base backup.
Enable archiving
archive_mode requires a restart; archive_command only a reload. The command must fail (non-zero exit) if the segment
is not safely stored, and must not overwrite an existing file:
ALTER SYSTEM SET archive_mode = on;
ALTER SYSTEM SET archive_command = 'test ! -f /archive/%f && cp %p /archive/%f';
After docker restart pg-b, switching the WAL segment forces the first archive and pg_stat_archiver confirms it:
SELECT pg_switch_wal();
SELECT archived_count, last_archived_wal, failed_count FROM pg_stat_archiver;
archived_count | last_archived_wal | failed_count
----------------+--------------------------+--------------
1 | 00000001000000000000000A | 0
A local cp into a Docker directory is a teaching setup. In production the archive must be on different storage from the
data (object storage via a tool such as pgBackRest or WAL-G, described below). Setting archive_timeout bounds how much
recent data an idle server can lose by forcing a segment switch periodically.
Take the base backup, then lose data
A new base backup is taken (this is the /backup/base from the previous section). Then the data changes and a disaster
happens:
UPDATE shop.orders SET status = 'shipped' WHERE id = 1002;
INSERT INTO shop.customers VALUES ('c-5', 'Edsger Dijkstra', 'edsger@example.com', 'Nuenen', 'pro', now());
SELECT now(); -- 2026-11-10 19:08:43.547937+00 (the recovery target)
DROP TABLE shop.order_items CASCADE; -- the mistake
SELECT pg_switch_wal(); -- archive the segment that contains the mistake
The destructive change is now durable and archived. The recovery target is the timestamp printed just before the DROP.
Restore and replay to the target
Copy the base backup to a new directory, tell the server how to fetch WAL, and create recovery.signal so it starts in
targeted archive recovery. The example starts the recovered cluster on port 5433 in the same container; a real recovery
would use a new host or an empty data directory with the service stopped.
cp -a /backup/base/. /restore/ && chmod 700 /restore
cat >> /restore/postgresql.auto.conf <<EOF
restore_command = 'cp /archive/%f %p'
recovery_target_time = '2026-11-10 19:08:43.547937+00'
recovery_target_action = 'promote'
archive_mode = off
EOF
touch /restore/recovery.signal
pg_ctl -D /restore -o "-p 5433" -l /tmp/restore.log -w start
The server log narrates the recovery (trimmed to the key lines):
LOG: starting backup recovery with redo LSN 0/B000028, checkpoint LSN 0/B000080, on timeline ID 1 LOG: restored log file "00000001000000000000000B" from archive LOG: starting point-in-time recovery to 2026-11-10 19:08:43.547937+00 LOG: redo starts at 0/B000028 LOG: restored log file "00000001000000000000000C" from archive LOG: restored log file "00000001000000000000000D" from archive LOG: consistent recovery state reached at 0/B000120 LOG: database system is ready to accept read-only connections LOG: recovery stopping before commit of transaction 958, time 2026-11-10 19:08:45.581869+00 LOG: redo done at 0/D00B4B8 LOG: selected new timeline ID: 2 LOG: archive recovery complete LOG: database system is ready to accept connections
The cp: cannot stat '/archive/00000002.history' messages in the full log are normal: recovery probes for timeline
history files that do not exist yet. Recovery stopped before the transaction that dropped the table, and the server
switched to timeline 2. Checking the result:
SELECT pg_is_in_recovery(); -- f
SELECT count(*) FROM shop.order_items; -- 11 (the dropped table is back)
SELECT id, status FROM shop.orders WHERE id = 1002; -- shipped (the committed update survived)
SELECT count(*) FROM shop.customers; -- 5 (the committed insert survived)
pg_is_in_recovery | f count | 11 1002 | shipped count | 5
(The four results are shown condensed.) Recovery target options are recovery_target_time, recovery_target_xid,
recovery_target_lsn, recovery_target_name (created with pg_create_restore_point()) and recovery_target = 'immediate'. recovery_target_inclusive chooses whether to stop just after or just before the target, and
recovery_target_action is pause (the default, to inspect first), promote or shutdown. Choosing pause and
checking the data before running pg_wal_replay_resume() is the safer habit when the exact target is uncertain.
After a recovery the old timeline’s WAL stays in the archive next to the new timeline’s; each timeline has a distinct numeric prefix in its file names, so a later recovery can target either.
Incremental backups
PostgreSQL 17 added incremental physical backups. With summarize_wal = on the server records which blocks changed, and
pg_basebackup --incremental copies only those relative to a previous manifest. pg_combinebackup reconstructs a full
backup from the chain, which pg_verifybackup then validates:
psql -U postgres -c "ALTER SYSTEM SET summarize_wal = on" -c "select pg_reload_conf()"
pg_basebackup -U postgres -D /backup/full -X stream -c fast
pg_basebackup -U postgres -D /backup/incr1 -i /backup/full/backup_manifest -X stream -c fast
pg_combinebackup /backup/full /backup/incr1 -o /backup/combined
pg_verifybackup /backup/combined
backup successfully verified
This was executed on a tiny database where incremental savings are not representative; the benefit appears with large databases that change a small fraction of their blocks between backups.
Choosing a strategy
| Approach | Recovery point | Best for |
|---|---|---|
|
The moment of the dump |
Small and medium databases, major upgrades, copying one schema or table |
|
The end of the backup |
Seeding a standby, whole-cluster copies |
Base backup plus WAL archive |
Any moment, down to the last archived WAL |
Production databases; recovery from operator error |
Replication standby |
Seconds behind, near zero |
High availability, but it replicates mistakes too; not a backup |
A replica is not a backup: a DROP TABLE replicates immediately. Combine a standby for availability with archived
backups for history.
Tools that automate this
Hand-rolled cp archiving is shown for understanding; production systems normally use a purpose-built tool:
-
pgBackRest — parallel, compressed and encrypted full, differential and incremental backups, repository on S3, GCS or Azure, retention policies,
restore --type=time, and backup verification. -
Barman (Backup and Recovery Manager) — a central backup server that pulls base backups and WAL over the replication protocol or SSH and manages retention and recovery for many servers.
-
WAL-G — a WAL archiver and backup tool oriented to object storage.
-
Managed services and Kubernetes operators typically wrap one of these.
These tools are mentioned for orientation only and were not run here.
Testing your backups
-
Restore regularly to a scratch server and run application checks; schedule it, do not wait for an incident.
-
Run
pg_verifybackupafter every base backup andpg_amcheckon the restored copy to detect corrupt index and heap pages. -
Enable data checksums (
initdb --data-checksums, the default since PostgreSQL 18) so storage corruption is detected at read time. -
Monitor
pg_stat_archiver.failed_countand the age oflast_archived_time; a silently failingarchive_commandfills the WAL directory and eventually stops the server. -
Record the recovery time you measured, and compare it with your recovery time objective.
Related pages
-
Architecture (WAL and checkpoints)