How to Back Up a PostgreSQL Database in Docker
Backing up PostgreSQL in Docker gives you a portable copy you can restore after data loss, a failed change, or a move to another server. The most reliable everyday approach is to run PostgreSQL’s pg_dump inside the database container and save its output on the host, where you can copy it to separate storage.
What You’ll Need
- A running PostgreSQL container and permission to use Docker commands.
- The database name and a PostgreSQL user with permission to read the database.
- Enough free space on the host for the backup, plus a destination outside the container for long-term storage.
- If you use Docker Compose, the Compose file and the service name for PostgreSQL.
Step-by-Step
- Find the container and database details. Run
docker psto locate the PostgreSQL container. Note its name or ID. If you are unsure of the database name or user, inspect the container’s configuration withdocker inspect CONTAINER_NAMEand look for environment variables such asPOSTGRES_DBandPOSTGRES_USER. Treat this output as sensitive; it may reveal configuration secrets. These variables describe initialization settings and might not reflect later changes to database roles or names. - Choose a backup format. For a single database, use PostgreSQL’s custom archive format with
pg_dump -Fc. It is compressed and can be restored selectively usingpg_restore. A plain SQL backup is also useful when you want a readable script; omit-Fcto create one. The examples below use the custom format. - Create the backup on the host. Replace the placeholders with your actual values, then run this from a host shell:
docker exec -t CONTAINER_NAME pg_dump -U DB_USER -d DB_NAME -Fc > backup.dump
The shell redirects the command’s output tobackup.dumpon the host, not inside the container. For example, a container calledpostgresmight usedocker exec -t postgres pg_dump -U appuser -d appdb -Fc > appdb-2026-11-08.dump. Use a date in the filename so backups are easy to identify. The database user may be prompted for a password; avoid putting passwords directly in shell commands, where they can appear in history or process listings. - Check that the command succeeded. Check the command’s exit status immediately: on Linux or macOS, run
echo $?; in PowerShell, inspect$LASTEXITCODE. A zero exit status indicates success. Check that the file exists and is not empty, for example withls -lh backup.dumpon Linux/macOS orGet-Item backup.dumpin PowerShell. A file’s existence alone does not prove it is valid, so proceed to test a restore. - For Docker Compose, use the service name. From the directory containing the Compose file, run
docker compose exec -T SERVICE_NAME pg_dump -U DB_USER -d DB_NAME -Fc > backup.dump. ReplaceSERVICE_NAMEwith the database service key in the Compose file. The-Toption disables a pseudo-terminal, which helps keep redirected output clean. If the service is not running, start it before backing up. - Test the archive by restoring it to a separate database. Create a scratch database, then use
pg_restoreto load the archive. For example, if the container has a suitable PostgreSQL client and a database namedrestore_testexists, rundocker exec -i CONTAINER_NAME pg_restore -U DB_USER -d restore_test --no-owner < backup.dump. Use a separate test database, never an existing production database. Review any errors and verify important tables and records. The restore client should be compatible with the archive and database versions; consult PostgreSQL’s version compatibility guidance if they differ. - Store and rotate copies safely. Copy successful backups off the Docker host to storage with restricted access. Keep more than one recent copy and periodically repeat the restore test. A backup stored only on the same machine does not protect you from losing that machine.
Common Mistakes
- Saving the file inside the container: Container files can disappear when a container is removed. Put the shell redirection on the host, as shown, or explicitly bind-mount a host directory.
- Using the wrong container, user, or database: Confirm names before running the dump. A successful dump of the wrong database is still the wrong backup.
- Assuming a mounted data volume is a complete backup: Copying PostgreSQL’s live data directory is not a substitute for a database-aware backup. A raw filesystem copy can be inconsistent unless it is made using a supported snapshot or backup procedure.
- Ignoring errors or empty files: A failed command may still leave a file behind. Check the exit status and test the archive.
- Putting a password in the command line: Avoid forms such as
-Wpassword. Use a securely managed PostgreSQL password file, an interactive prompt where practical, or another approved secret-management method.
Tips
- For large databases or repeatable jobs, use a script that records the date, checks the dump’s exit status, logs errors, and alerts you if a backup fails.
- To avoid overwriting a good backup after an unsuccessful run, write to a temporary filename and rename it only after
pg_dumpsucceeds. - A full-cluster backup needs more than one database dump. Use
pg_dumpall --globals-onlyto capture cluster-wide roles and tablespaces, and keep that output protected because it can contain sensitive role information. Individual databases still need their own dumps. - For point-in-time recovery or very large databases, investigate PostgreSQL’s physical backup and WAL archiving options. A regular
pg_dumpis a logical backup, not a continuous recovery system.
Troubleshooting
- “No such container” or “service not running”: Run
docker psand confirm the container name. With Compose, rundocker compose psand use the database service name, not necessarily the container name. - “Connection refused”: Check that PostgreSQL is running and ready. Review container logs with
docker logs CONTAINER_NAMEordocker compose logs SERVICE_NAME, and retry once startup has completed. - “Role does not exist” or “database does not exist”: Verify the actual role and database names. Initialization environment variables do not necessarily describe a database that has since been changed.
- Password authentication failed: Confirm the correct credentials and authentication setup. Do not expose passwords in terminal history or logs; use a protected credential file or secret mechanism.
- The dump file is empty or restore reports an invalid archive: Check the dump command’s exit status and stderr. Make sure output was redirected on the host and that the command used
-Fcif you plan to usepg_restore. Plain SQL dumps should instead be loaded withpsql. - Permission denied or disk full: Choose a host directory your account can write to and check available space with
df -hon Linux/macOS. On Windows, check the destination drive’s free space and directory permissions.
Frequently Asked Questions
Does docker commit back up PostgreSQL data?
No. It saves a container image, not a reliable, consistent database backup. Use PostgreSQL backup tools such as pg_dump.
Can PostgreSQL stay online during pg_dump?
Yes. pg_dump creates a consistent logical snapshot while the database is in use, though a large dump can consume resources.
How do I restore a custom-format backup?
Create a target database, then run pg_restore -U DB_USER -d TARGET_DB backup.dump from a location where the file is accessible. Review ownership and role requirements before restoring.
How often should I back up?
Choose a schedule based on how much recent data you can afford to lose and how often the database changes. Automate backups and verify restores regularly.
Does pg_dump include roles and passwords?
No. It backs up one database’s contents, not cluster-wide roles. Use pg_dumpall --globals-only for global objects, and protect that file carefully.
Can I back up to a compressed file?
Yes. The custom format from pg_dump -Fc is compressed by default and can be restored with pg_restore.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.