pg_dumppg_dump is a flexible tool for logical backups, creating SQL scripts or custom-format archives that can be restored on other PostgreSQL instances.
-U for the username, -d for the database name, -f to specify the output file, and -F to set the format (e.g., t for tar, c for custom).pg_dump -U postgres -h localhost -p 5432 -F t mydb > mydb_backup.tar.gzip to reduce file size (e.g., pg_dump -U postgres -d mydb | gzip > mydb_backup.sql.gz). This is recommended for large databases.pg_dumpall (run as postgres user) to back up all databases, including roles and tablespaces.sudo -u postgres pg_dumpall -f /path/to/all_databases.sql.pg_basebackupFor large databases or whole-cluster recovery, pg_basebackup creates a physical copy of the data directory, including WAL (Write-Ahead Logging) files.
-D to specify the backup directory, -F for the format (e.g., t for tar), -z to compress, and -P to show progress.pg_basebackup -D /pg_basebackup -F t -z -P -h localhost -p 5432 -U postgres.Schedule regular backups using cron to avoid manual intervention.
crontab -e) to run a daily pg_dump at 1 AM:0 1 * * * /usr/bin/pg_dump -U postgres -h localhost -p 5432 -F t mydb | gzip > /path/to/backups/mydb_$(date +\%Y\%m\%d).tar.gz.psql to execute the SQL script.psql -U postgres -d mydb -f /path/to/mydb_backup.sql.pg_restore for compressed or custom-format backups.pg_restore -U postgres -d mydb /path/to/mydb_backup.tar.gzpg_restore -U postgres -d mydb /path/to/mydb_backup.tar.sudo systemctl stop postgresql.cp -r /pg_basebackup/* /var/lib/postgresql/data/.sudo systemctl start postgresql.PITR allows restoring the database to a specific time or transaction, ideal for recovering from accidental deletions or corruption.
postgresql.conf to turn on archiving and set the WAL level.wal_level = replica
archive_mode = on
archive_command = 'test -d /usr/local/pgsql/arch/$(date +%Y%m%d) || mkdir -p /usr/local/pgsql/arch/$(date +%Y%m%d); cp %p /usr/local/pgsql/arch/$(date +%Y%m%d)/%f'
```.
pg_basebackup to take a full backup before enabling PITR.pg_basebackup -D /backup/full_backup -F t -z -P -h localhost -p 5432 -U postgres.postgresql.auto.conf in the data directory with restore and recovery parameters:restore_command = 'cp /usr/local/pgsql/arch/$(date +%Y%m%d)/%f %p'
recovery_target_time = '2025-09-25 14:30:00'
recovery_target_timeline = 'latest'
```.
Regularly test backups to ensure they are valid and can be restored successfully.
pg_restore with the --list option to view the contents of a custom-format backup without restoring it.pg_restore --list /path/to/mydb_backup.tar.pg_verifybackup (available in PostgreSQL 14+) to validate the integrity of physical backups.postgres user (or a user with sufficient privileges) to avoid permission issues.