Backups
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.gzpg_wal.tar.gzbackup_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 startLogical 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_dumpdoes not include cluster-wide roles and tablespaces — back those up separately withpg_dumpall --globals-only.
| Flag | Purpose | Why It Matters |
|---|---|---|
-F p | Plain SQL format | Widely portable and readable |
--encoding=UTF8 | Force UTF-8 output | Avoids locale/charset issues |
--no-owner | Skip ownership | Avoids permission mismatches |
--no-privileges | Skip GRANTs | Simplifies cross-environment restore |
--blobs | Include large objects | Ensures all data included |
--serializable-deferrable | Transaction-safe dump | Consistency for live systems |
--no-comments | Skip comments | Reduces noise, increases diffability |
Restore a gzipped plain SQL dump:
gunzip -c mydatabase_2025-10-29.sql.gz | psql -U postgres -d mydatabaseParallel 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_dirUsing 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