Back up a Postgres database running in Docker
You back up Postgres in Docker by running pg_dump inside the database container and saving the output to a file outside it.
- Updated Nov 27, 2026
- Markdown
Dump a Postgres database from a Compose service to a file, copy it off the server and schedule it.
- A Postgres service named db in Docker Compose
- SSH access to the server
To back up Postgres in Docker, run pg_dump inside the database container and redirect its output to a file on the host. The file is a consistent copy of that one database that you can restore on any machine with a compatible Postgres.
How it works#
pg_dump connects to Postgres like any client and asks for a snapshot. It starts a transaction, reads each table as it was when the transaction began, and writes either SQL statements (plain format) or a compressed archive (custom format). Other clients keep reading and writing while it runs, and the dump stays consistent because Postgres gives it a fixed view of the data.
Copying the volume’s raw files is a different thing. The files change while you copy them, so the result may not start. That is why the logical dump is the standard way for a database that stays online.
In Docker, you do not need pg_dump on the host. The container already has it, in the version that matches the server. docker compose exec runs it there, and the shell redirect > captures the output on the host. This lesson assumes a Compose service named db, a database user USER and a database DBNAME. Change them to yours. For the wider plan of copies and locations, see Backups and the 3-2-1 rule.
Step 1: Dump to a plain SQL file#
docker compose exec -T db pg_dump -U USER DBNAME > backup.sql-T disables the terminal so the redirect works. -U USER picks the database role. To save space, compress it:
docker compose exec -T db pg_dump -U USER DBNAME | gzip > backup.sql.gzWhat you should see: no output on screen. A backup.sql or backup.sql.gz file appears, larger than zero bytes. A progress message would mean something went wrong, so read any text that appears.
Step 2: Or use the custom format#
docker compose exec -T db pg_dump -U USER -Fc DBNAME > backup.dump-Fc writes the custom format. It is compressed by default and restored with pg_restore, which also allows restoring single tables and reordering. A plain file is restored with psql. You cannot feed a custom file to psql.
What you should see: again no output, and a backup.dump file. head -c 5 backup.dump prints PGDMP, the format marker.
Step 3: Save roles and globals#
docker compose exec -T db pg_dumpall -U USER -g > globals.sql-g dumps only global objects, such as roles. A single-database dump does not include them, so a restore on a fresh server can fail on missing roles.
What you should see: a globals.sql file with CREATE ROLE lines. It can contain password hashes, so treat it as secret.
Step 4: Copy it off the server#
scp user@your-server:/path/to/backup.sql.gz .Do this from your own machine. Keep copies somewhere other than the server. rsync is better for repeated copies, since it sends only what changed.
What you should see: a progress line with the file name and size, then your prompt.
Step 5: Schedule it with cron#
Run crontab -e and add a nightly job (adjust the path):
0 3 * * * cd /srv/app && docker compose exec -T db pg_dump -U USER -Fc DBNAME > /srv/backups/db-$(date +\%F).dumpThe five fields mean 03:00 every day. In cron, % must be escaped as \%. Delete old files on a schedule you choose, or the disk will fill.
What you should see: crontab -l lists the line. The next morning a new dated file is in /srv/backups. See Schedule tasks with cron for more.
Check it worked#
ls -lh backup.sql.gz
gunzip -c backup.sql.gz | headThe file should be larger than zero bytes, and the start of a plain dump shows SQL comments and SET statements. For a custom dump, docker compose exec -T db pg_restore --list < backup.dump | head lists the contents. A backup you have not restored is not proven, so continue to the next lesson.
Edge cases and gotchas#
- A failed dump leaves an empty or partial file. The shell creates the file before
pg_dumpruns. Dump to a temporary name, check the exit code, then rename it. - Cron has a bare environment.
dockermay not be on itsPATH, and the working directory is your home. Usecdinto the project and the full path/usr/bin/dockerif needed. - Version mismatch on restore. A dump from a newer major Postgres may not load into an older server. Restore into the same or a newer version.
- The service name is not the container name.
docker compose exec dbuses the service name fromcompose.yaml.docker execneeds the container name. - Passwords in the command line. Avoid putting passwords in
pg_dumparguments. Inside the container, the local socket often allows access for the configured user without one. - Large databases are slow to dump and restore. The dump competes with your app for disk and CPU. Run it at a quiet hour and watch the load.
- Dump size on small disks. A plain dump can be several times the compressed size. Check free space with
df -hbefore you start. - Dumps contain personal data. Set
chmod 600and encrypt copies that leave the server.
Troubleshooting#
| Symptom | Likely cause | Fix |
|---|---|---|
Empty backup.sql | The command failed after the redirect created the file | Run without > and read the error |
pg_dump: error: connection to server on socket ... failed | Postgres is not ready or not running | Check docker compose ps and the db logs |
role "postgres" does not exist | Your image uses another superuser, set by POSTGRES_USER | Use that name with -U |
FATAL: database "DBNAME" does not exist | Wrong database name | List with docker compose exec db psql -U USER -l |
service "db" is not running | The db container is stopped | docker compose up -d db |
| Garbage characters in a plain file | -T missing | Add -T |
pg_dump: error: aborting because of server version mismatch | Client and server major versions differ | Run pg_dump inside the container, which matches the server |
| Cron job never creates a file | % not escaped, or docker not in PATH | Escape % as \% and use full paths |
| Disk fills up | No cleanup of old dumps | Delete files older than your retention period |
Real-world scenario#
A small SaaS runs Postgres in Compose. The founder adds a nightly job and copies the files to a second server. Three weeks later the db container is renamed in the compose file, from db to postgres. The cron line still says db, so it fails every night and writes zero-byte files.
A weekly glance at the folder shows files of 0 bytes. They run the command by hand without the redirect and read service "db" is not running. They update the service name, rewrite the job to write to a temporary file and move it only on success, and add a check that alerts when the newest file is under a size they pick. Then they restore the next dump into a scratch database to confirm it works.
Quick reference#
| Task | Command |
|---|---|
| Plain dump | docker compose exec -T db pg_dump -U USER DBNAME > backup.sql |
| Compressed plain dump | ... | gzip > backup.sql.gz |
| Custom format | docker compose exec -T db pg_dump -U USER -Fc DBNAME > backup.dump |
| Roles only | docker compose exec -T db pg_dumpall -U USER -g > globals.sql |
| Restore plain | psql -U USER -d DBNAME < backup.sql |
| Restore custom | pg_restore -U USER -d DBNAME backup.dump |
| Cron percent | write % as \% |
Security and safety notes#
- Dumps hold real user data. Restrict permissions and encrypt copies that leave the server.
- Never store a dump in a web-served folder.
- Do not delete old backups until a newer one has been restored successfully at least once.
Related lessons#
- Backups and the 3-2-1 rule: how many copies and where to keep them
- Docker volumes and persistent data: where Postgres keeps its files
- Schedule tasks with cron: the schedule syntax used above
- Self-hosted Postgres in Docker: connecting an app to the database
Next#
Prove the file works: Test a backup by restoring it.
Check what you learned
Frequently asked questions
Is copying the Postgres volume enough as a backup?
Copying files of a running database can give an inconsistent copy. A pg_dump gives a consistent snapshot you can restore with standard tools.
Where should the Postgres backup file live?
Not only on the same server. Copy it to another machine or storage, so losing the server does not lose the backups.
Does pg_dump back up users and all databases?
No. It saves one database. Roles and other databases need pg_dumpall, for example pg_dumpall -g for roles and tablespaces only.
Why is my pg_dump file empty?
The command failed, usually on a wrong user, database or service name. The redirect still creates the file. Run the command without the redirect to read the error.
Sources
Keep going: guides and tutorials
- Zero Downtime Deploy for Docker Apps, With Rollback How a Docker deploy waits for readiness before cutover, holds the previous release for rollback, rolls back on its own, and how to rehearse it.
- Roll Back a Failed Docker Deploy Without Downtime Ship a broken release on purpose, watch your users stay on the old version, then roll back with one command. Real commands, real output, self-hosted.
- Our Health Check Failed and the Deploy Went Live Anyway A postmortem from our own dogfood run: a failed readiness probe still received traffic. What broke, why two correct parts added up to a bug, and the fix.