Illustrated title card for the guide: Safe Docker PostgreSQL Backups With pg_dump and NAS
database-backups

Safe Docker PostgreSQL Backups With pg_dump and NAS

Back up Docker PostgreSQL safely to a NAS using pg_dump and pg_dumpall, secure credentials with .pgpass, and verify restores with pg_restore.

To back up a running Docker PostgreSQL container to a NAS safely, export logical dumps with pg_dump and pg_dumpall --globals-only into a dedicated backup folder on your NAS. Direct file copies of an active PostgreSQL data directory are unsafe while the database server runs. pg_dump produces internally consistent backups and generally allows other database operations to continue. Operations that require an exclusive lock, such as most forms of ALTER TABLE, can be blocked.

Evidence and limits. Checked on 2026-11-26 against the PostgreSQL 19 documentation, Docker CLI reference, and official Docker postgres image documentation. This guide is not based on hands-on testing.

Why copying a live PostgreSQL data directory fails

Copying the PostgreSQL data directory directly while the database server is running risks an unusable backup. The PostgreSQL File System Level Backup documentation requires shutting down the database server for a direct copy made with a tool such as tar and before restoring it.

Disallowing all connections does not make a plain file copy safe. Tools like tar do not take an atomic file-system snapshot, and PostgreSQL also buffers data internally.

A consistent frozen snapshot can be taken while the server runs if the file system supports it. Include the WAL files in the backup and take snapshots of all involved volumes simultaneously. A continuous-archiving base backup can also run while the server is up.

Backup methodDatabase server stateScopeVersion portabilityRestore tool
Logical dump (pg_dump + pg_dumpall -g)Running (pg_dump can block operations that require an exclusive lock)Individual databases plus cluster-wide globalspg_dump output generally loads into PostgreSQL versions newer than the pg_dump versionpg_restore and psql
Direct file-system copyCompletely shut down for full copy and restoreEntire database clusterServer-version-specificFull-cluster file restore
Continuous archiving and WAL (PITR)Running (continuous archiving + WAL)Server-version-specificContinuous archive recovery

Point-in-Time Recovery (PITR) with WAL archiving and NAS-specific backup application configuration are outside this setup guide. See the homelab backup guides index. Browse backup guides by topic.

Choosing pg_dump custom format and pg_dumpall globals

PostgreSQL provides two complementary logical dump utilities.

  • pg_dump backs up a single database into a plain SQL script or an archive file. Passing custom format (-Fc or --format=custom) creates an archive for pg_restore that supports selective restoration, item reordering, and parallel restoration. By default, gzip compresses individual table-data segments at a moderate level.
  • pg_dumpall extracts an entire cluster, including the database roles, tablespaces, and configuration-parameter privilege grants that pg_dump omits. Passing -g or --globals-only exports only global objects, such as roles and tablespaces, and skips all databases.

Combining pg_dump -Fc for each database with pg_dumpall --globals-only keeps archive flexibility while preserving cluster-wide roles. With a full pg_dumpall, each database dump is internally consistent. The PostgreSQL SQL Dump documentation specifies that snapshots across different databases are not synchronized.

Before running the dump commands, confirm the database name and the PostgreSQL role you will connect as. In the official Docker postgres image documentation, POSTGRES_USER sets the initial superuser role (default postgres), POSTGRES_DB sets the initial database (defaulting to POSTGRES_USER), and PGDATA sets the cluster data path. The image uses POSTGRES_USER and POSTGRES_DB to initialize a database only when the container starts with an empty data directory.

Exporting dumps from Docker and Docker Compose

Keep pseudo-TTY allocation disabled for the redirected dump commands below.

Use fresh output paths for both files on every run. Create a new subdirectory under your backup folder and use its path in the export commands below. Check that both pg_dump and pg_dumpall succeeded before treating the new files as a backup.

The pg_dump examples assume <db_user> has read access to every table in the database. A complete pg_dumpall dump usually requires a database superuser, and the globals examples assume that privilege. The globals script includes role password data by default, so restrict access to globals.sql.

  • docker exec (documented under docker container exec in Docker Docs) does not allocate a pseudo-TTY by default. Omit -t (--tty) when redirecting dump output to a file. Use -i (--interactive) to keep standard input open when sending input to the container.
  • docker compose exec (Docker Docs) allocates a pseudo-TTY by default. Pass -T (--no-tty) to disable pseudo-TTY allocation. Compose keeps standard input open by default. For output-only automation, also pass --interactive=false to disable interactive input.

Standalone Docker dump commands

Run these commands from the host to write a custom-format archive and a globals script to a local or NAS-mounted backup folder. Replace <container>, <db_user>, <db_name>, and /path/to/pg-backups with your values.

docker exec <container> pg_dump -Fc -U <db_user> -d <db_name> > /path/to/pg-backups/<db_name>.dump
docker exec <container> pg_dumpall --globals-only -U <db_user> > /path/to/pg-backups/globals.sql

If the NAS backup directory is already mounted at /backups in the container, use -f (--file) to write the dumps directly there.

docker exec <container> pg_dump -Fc -U <db_user> -d <db_name> -f /backups/<db_name>.dump
docker exec <container> pg_dumpall --globals-only -U <db_user> -f /backups/globals.sql

Docker Compose dump commands

Use -T and --interactive=false for these output-only dumps, and replace <service> with your PostgreSQL service name.

docker compose exec -T --interactive=false <service> pg_dump -Fc -U <db_user> -d <db_name> > /path/to/pg-backups/<db_name>.dump
docker compose exec -T --interactive=false <service> pg_dumpall --globals-only -U <db_user> > /path/to/pg-backups/globals.sql

You can override the default gzip compression on custom-format archives with -Z or --compress (PostgreSQL supports gzip, lz4, zstd, or none). The pg_dump option --no-owner (-O) applies only to plain-text output. To skip restoring ownership from a custom archive, pass --no-owner to pg_restore.

Command / FlagToolDocumented purpose
-T, --no-ttydocker compose execDisables pseudo-TTY allocation
-i, --interactivedocker execKeeps STDIN open even if unattached
-u, --userdocker compose execRuns the command as the specified user
-Fc, --format=custompg_dumpCreates a pg_restore archive with default compression and support for selective and parallel restores
-U, --usernamepg_dump, pg_dumpall, pg_restoreSpecifies the PostgreSQL role used to connect
-d, --dbnamepg_dump, pg_restoreSelects the database name to connect to
-f, --filepg_dump, pg_dumpallWrites these dumps to the specified file instead of standard output
-Z, --compresspg_dumpSets the compression method (gzip, lz4, zstd, or none), level, or both
-g, --globals-onlypg_dumpallDumps global objects such as roles and tablespaces and skips all databases

Credential handling for automated dumps

Avoid passing database passwords through PGPASSWORD in automated scripts. The PostgreSQL Environment Variables documentation warns that PGPASSWORD is not recommended for security reasons because some operating systems let non-root users inspect process environment variables with ps.

Also avoid setting POSTGRES_HOST_AUTH_METHOD=trust to bypass passwords. The official Docker postgres documentation advises against trust because it permits host connections without a password.

When the connection requires a password and none was specified, put a PostgreSQL password file (.pgpass) in the home directory of the user running the client inside the container. Use the field order hostname:port:database:username:password. The first four fields accept * as a wildcard. Escape a literal : or \ within a field with a backslash. On Unix systems, libpq ignores .pgpass if the file allows any group or world access. Restrict its permissions before use.

chmod 0600 ~/.pgpass

Verifying and restoring PostgreSQL dumps

Inspect the archive from your NAS, then restore the dumps into PostgreSQL to check that the restore works.

Inspecting a custom archive before restoring

List the recovered archive’s table of contents with pg_restore --list (-l). When no filename argument is passed, pg_restore reads the archive from standard input.

docker exec -i <container> pg_restore --list < /path/to/recovery/<db_name>.dump

With Docker Compose, use -T and leave interactive input enabled so pg_restore can read the archive from standard input.

docker compose exec -T <service> pg_restore --list < /path/to/recovery/<db_name>.dump

Restoring globals and databases

Restore cluster-wide roles and tablespaces first as a database superuser, with any required tablespace directories already in place. For both restore commands, replace <restore_container> with the name of a fresh, disposable destination container. Initialize it with a different bootstrap superuser name from the source. By default, psql continues after SQL errors. Pass --set ON_ERROR_STOP=on as shown in the PostgreSQL SQL Dump documentation to stop on the first SQL error.

docker exec -i <restore_container> psql -X --set ON_ERROR_STOP=on -U <db_superuser> postgres < /path/to/recovery/globals.sql

Destructive restore warning. The --clean (-c) flag instructs pg_restore to drop the objects it will restore. With --create (-C), it drops and recreates the database named in the archive.

To recreate and populate the database named inside the custom archive, set <maintenance_db> to an existing database other than the one in the archive.

docker exec -i <restore_container> pg_restore --clean --if-exists --create --exit-on-error -U <db_superuser> -d <maintenance_db> < /path/to/recovery/<db_name>.dump

The pg_restore options work as follows.

  • -C (--create), used here with --clean, uses the database specified by -d only for the initial DROP DATABASE and CREATE DATABASE commands. The restore goes into the database named in the archive.
  • --if-exists requires --clean and uses DROP ... IF EXISTS to suppress errors for objects that are missing from the destination.
  • --exit-on-error stops the restore if an error occurs while sending SQL commands to the database. By default, pg_restore continues and prints an error count at the end.
  • -1 (--single-transaction) wraps the restore in one BEGIN / COMMIT block and implies --exit-on-error. PostgreSQL documents that --single-transaction cannot be combined with --create or parallel --jobs (-j).
  • -j (--jobs) enables parallel restoration on custom or directory archives when pg_restore connects directly to the database. It requires a regular file or directory as input. For -j with docker exec, pass pg_restore the archive path inside the container.

Sources

  1. PostgreSQL Documentation: SQL Dump
  2. PostgreSQL Documentation: File System Level Backup
  3. PostgreSQL Documentation: pg_dump
  4. PostgreSQL Documentation: pg_dumpall
  5. PostgreSQL Documentation: pg_restore
  6. PostgreSQL Documentation: The Password File
  7. PostgreSQL Documentation: Environment Variables
  8. Docker Docs: docker container exec
  9. Docker Docs: docker compose exec
  10. Docker Official Images: postgres Documentation

Related