PostgreSQL Backups: What is pg_basebackup?
- pg_basebackup is a simple yet powerful utility provided by PostgreSQL for taking online and consistent file system-level backups.
- The backups created using this command include the actual database files, allowing for straightforward restoration: simply uncompress the backup files and copy them to the database data directory.
- This utility can create base backups of your database cluster, which can be used for point-in-time recovery. Additionally, pg_basebackup supports setting up a standby replica database server using its streaming option.
- In this guide, we will explore the process of creating backups using the pg_basebackup utility and delve into the various options available for this task.
Tablespace Information
You ran:
psql -c “select oid, spcname, pg_tablespace_location(oid) from pg_tablespace”
Result:
| OID | Tablespace Name | Location |
| 1663 | pg_default | (inside data directory) |
| 1664 | pg_global | (inside data directory) |
| 16419 | TBS2 | /var/lib/pgsql/backup/TBS2 |
| 16420 | TBS3 | /var/lib/pgsql/backup/TBS3 |
So you have two external tablespaces: TBS2 and TBS3
1. Backup in TAR + Compressed Format
pg_basebackup -h localhost -p 5432 -U postgres -D /var/lib/pgsql/backup -Ft -z -Xs -P
Explanation of Parameters
| Parameter | Meaning |
| -h localhost | Connect to PostgreSQL running on local host |
| -p 5432 | PostgreSQL port number |
| -U postgres | User performing the backup (must have REPLICATION role) |
| -D /var/lib/pgsql/backup | Directory where backup files should be stored |
| -F t | Format = TAR archive |
| -z | Compress the TAR output (creates .tar.gz files) |
| -X s | Include WAL files in backup (stream mode) |
| -P | Show progress |
2. Backup in Plain Directory Format
pg_basebackup -h localhost -p 5432 -U postgres -D /var/lib/pgsql/backup -Fp -Xs -P
Explanation
| Parameter | Meaning |
| -F p | Format = Plain directory (exact data directory copy) |
| -Xs | Stream WAL files and include in backup directory |
| -P | Show progress |
Important Note
Plain format will fail if tablespace directories already exist and are not empty.
This is why tablespace mapping is used.
3. Backup with Tablespace Mapping
Run backup with mapping
pg_basebackup -D /var/lib/pgsql/backup -F p -R -P -X stream \
–tablespace-mapping=/var/lib/pgsql/TBS1=/var/lib/pgsql/backup/TBS2 \
–tablespace-mapping=/var/lib/pgsql/TBS3=/var/lib/pgsql/backup/TBS3
Explanation of Tablespace Mapping
| Parameter | Meaning |
| –tablespace-mapping=OLD=NEW | Redirects tablespace directory from its original location to new backup location |
So we are saying:
Store /data_pgbench → /var/lib/pgsql/backup/data_pgbenchStore /data_pgtest → /var/lib/pgsql/backup/data_pgtest
This ensures:
- No overwrite of existing tablespace directories
- Clean self-contained backup directory
- Safe restore on another server / instance





