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 method | Database server state | Scope | Version portability | Restore tool |
|---|---|---|---|---|
Logical dump (pg_dump + pg_dumpall -g) | Running (pg_dump can block operations that require an exclusive lock) | Individual databases plus cluster-wide globals | pg_dump output generally loads into PostgreSQL versions newer than the pg_dump version | pg_restore and psql |
| Direct file-system copy | Completely shut down for full copy and restore | Entire database cluster | Server-version-specific | Full-cluster file restore |
| Continuous archiving and WAL (PITR) | Running (continuous archiving + WAL) | Server-version-specific | Continuous 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_dumpbacks up a single database into a plain SQL script or an archive file. Passing custom format (-Fcor--format=custom) creates an archive forpg_restorethat supports selective restoration, item reordering, and parallel restoration. By default,gzipcompresses individual table-data segments at a moderate level.pg_dumpallextracts an entire cluster, including the database roles, tablespaces, and configuration-parameter privilege grants thatpg_dumpomits. Passing-gor--globals-onlyexports 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 underdocker container execin 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=falseto 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 / Flag | Tool | Documented purpose |
|---|---|---|
-T, --no-tty | docker compose exec | Disables pseudo-TTY allocation |
-i, --interactive | docker exec | Keeps STDIN open even if unattached |
-u, --user | docker compose exec | Runs the command as the specified user |
-Fc, --format=custom | pg_dump | Creates a pg_restore archive with default compression and support for selective and parallel restores |
-U, --username | pg_dump, pg_dumpall, pg_restore | Specifies the PostgreSQL role used to connect |
-d, --dbname | pg_dump, pg_restore | Selects the database name to connect to |
-f, --file | pg_dump, pg_dumpall | Writes these dumps to the specified file instead of standard output |
-Z, --compress | pg_dump | Sets the compression method (gzip, lz4, zstd, or none), level, or both |
-g, --globals-only | pg_dumpall | Dumps 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-donly for the initialDROP DATABASEandCREATE DATABASEcommands. The restore goes into the database named in the archive.--if-existsrequires--cleanand usesDROP ... IF EXISTSto suppress errors for objects that are missing from the destination.--exit-on-errorstops the restore if an error occurs while sending SQL commands to the database. By default,pg_restorecontinues and prints an error count at the end.-1(--single-transaction) wraps the restore in oneBEGIN/COMMITblock and implies--exit-on-error. PostgreSQL documents that--single-transactioncannot be combined with--createor parallel--jobs(-j).-j(--jobs) enables parallel restoration on custom or directory archives whenpg_restoreconnects directly to the database. It requires a regular file or directory as input. For-jwithdocker exec, passpg_restorethe archive path inside the container.