Chapter 4 · Lesson 11 of 18
Deploy and operate

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.

By the end you will

Dump a Postgres database from a Compose service to a file, copy it off the server and schedule it.

Time
22 min
Level
Intermediate
Check
4 questions
You need
  • 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#

bash
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:

bash
docker compose exec -T db pg_dump -U USER DBNAME | gzip > backup.sql.gz

What 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#

bash
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#

bash
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#

bash
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):

output
0 3 * * * cd /srv/app && docker compose exec -T db pg_dump -U USER -Fc DBNAME > /srv/backups/db-$(date +\%F).dump

The 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#

bash
ls -lh backup.sql.gz
gunzip -c backup.sql.gz | head

The 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_dump runs. Dump to a temporary name, check the exit code, then rename it.
  • Cron has a bare environment. docker may not be on its PATH, and the working directory is your home. Use cd into the project and the full path /usr/bin/docker if 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 db uses the service name from compose.yaml. docker exec needs the container name.
  • Passwords in the command line. Avoid putting passwords in pg_dump arguments. 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 -h before you start.
  • Dumps contain personal data. Set chmod 600 and encrypt copies that leave the server.

Troubleshooting#

SymptomLikely causeFix
Empty backup.sqlThe command failed after the redirect created the fileRun without > and read the error
pg_dump: error: connection to server on socket ... failedPostgres is not ready or not runningCheck docker compose ps and the db logs
role "postgres" does not existYour image uses another superuser, set by POSTGRES_USERUse that name with -U
FATAL: database "DBNAME" does not existWrong database nameList with docker compose exec db psql -U USER -l
service "db" is not runningThe db container is stoppeddocker compose up -d db
Garbage characters in a plain file-T missingAdd -T
pg_dump: error: aborting because of server version mismatchClient and server major versions differRun pg_dump inside the container, which matches the server
Cron job never creates a file% not escaped, or docker not in PATHEscape % as \% and use full paths
Disk fills upNo cleanup of old dumpsDelete 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#

TaskCommand
Plain dumpdocker compose exec -T db pg_dump -U USER DBNAME > backup.sql
Compressed plain dump... | gzip > backup.sql.gz
Custom formatdocker compose exec -T db pg_dump -U USER -Fc DBNAME > backup.dump
Roles onlydocker compose exec -T db pg_dumpall -U USER -g > globals.sql
Restore plainpsql -U USER -d DBNAME < backup.sql
Restore custompg_restore -U USER -d DBNAME backup.dump
Cron percentwrite % 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.

Next#

Prove the file works: Test a backup by restoring it.

Check what you learned4 questions
1Why does the dump command use docker compose exec -T?
2Why is copying the volume files of a running database a weak backup?
3In a cron line, how must a percent sign in date +%F be written?
4You dumped one database with pg_dump. What is missing from the backup?

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

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios