For continuous archiving and Point-In-Time Recovery with pgBackRest, see Point-In-Time Recovery.

Physical backups (pg_basebackup)#

Example using pg_basebackup:

pg_basebackup -D /tmp/pgbackup -F tar -z -X stream -c fast -P -U postgres

To run remotely, add -h with the PostgreSQL server IP:

pg_basebackup -h <postgresql-ip> -p 5432 -D /tmp/pgbackup -F tar -z -X stream -c fast -P -U postgres

This creates the backup archive in /tmp/pgbackup:

  • base.tar.gz
  • pg_wal.tar.gz
  • backup_manifest

Restoring a pg_basebackup archive#

Delete the existing PGDATA directory and extract the tar archives:

rm -rf /var/lib/postgresql/16
tar -xzf /tmp/pgbackup/base.tar.gz -C /var/lib/postgresql/16
tar -xzf /tmp/pgbackup/pg_wal.tar.gz -C /var/lib/postgresql/16/pg_wal

Start the PostgreSQL server:

pg_ctl -D /var/lib/postgresql/16 start

Logical backups (pg_dump & pg_dumpall)#

A logical backup captures the database contents as SQL commands (or a compressed custom archive) that can recreate the schema and data from scratch.

Logical backups are:

  • Portable across PostgreSQL major versions and platforms.
  • Human-readable (when using plain SQL).
  • Ideal for small to medium databases or schema/table-level restores.

Using pg_dump (plain SQL)#

pg_dump \
  -h <your IP> \
  -U <your user> \
  -F p \
  --encoding=UTF8 \
  --no-owner \
  --no-privileges \
  --blobs \
  --serializable-deferrable \
  mydatabase \
  | gzip > mydatabase_$(date +%F).sql.gz

pg_dump does not include cluster-wide roles and tablespaces — back those up separately with pg_dumpall --globals-only.

FlagPurposeWhy It Matters
-F pPlain SQL formatWidely portable and readable
--encoding=UTF8Force UTF-8 outputAvoids locale/charset issues
--no-ownerSkip ownershipAvoids permission mismatches
--no-privilegesSkip GRANTsSimplifies cross-environment restore
--blobsInclude large objectsEnsures all data included
--serializable-deferrableTransaction-safe dumpConsistency for live systems
--no-commentsSkip commentsReduces noise, increases diffability

Restore a gzipped plain SQL dump:

gunzip -c mydatabase_2025-10-29.sql.gz | psql -U postgres -d mydatabase

Parallel custom/directory dumps (pg_restore)#

For larger databases, use -Fc (custom) or -Fd (directory) format so you can dump and restore in parallel:

pg_dump -h localhost -U postgres -Fd -j 4 -f mydb_dir mydb
pg_restore -h localhost -U postgres -d mydb -j 4 --clean --if-exists mydb_dir

Using pg_dumpall#

Back up all databases and global objects (roles and tablespaces):

pg_dumpall -U postgres > full_backup.sql

Restore:

psql -U postgres -f full_backup.sql

Back up only globals (roles and tablespaces), then dump individual databases separately for more granular control:

pg_dumpall -U postgres --globals-only > globals.sql
pg_dump -U postgres mydb1 > mydb1.sql
pg_dump -U postgres mydb2 > mydb2.sql