pg_dump is a utility for exporting a PostgreSQL database into a file, which can be restored on the same or different servers. It exports a single database's tables, views, sequences, functions, indexes, triggers, and in-database grants but does not include roles, tablespaces, or server-level configurations. To capture global objects, pg_dumpall --globals-only should be executed prior to the per-database dump. pg_dump requires CONNECT and SELECT privileges on all tables and sequences within the target database, and a dedicated backup role is sufficient for single-database dumps, while superuser access is needed for global objects.
pg_dump supports various output formats: plain SQL (.sql), custom binary (.dump), directory of files, and tar archive (.tar), each with different capabilities for restoration and compression. The custom format allows for selective and parallel restoration. For non-interactive use, credentials can be stored in a .pgpass file or passed via the PGPASSWORD environment variable.
Restoration methods depend on the dump format: psql is used for plain SQL files, while pg_restore is used for custom and directory formats. The restoration process requires the target database to be created beforehand. Version mismatches between pg_dump and pg_restore can lead to failures, so it's essential to ensure that the binaries are version-matched.
In Docker, pg_dump and pg_restore can be executed within containers, but care must be taken to manage credentials and ensure version compatibility. Exit codes from pg_dump should be checked to confirm successful operations.