Chapter 9 · Lesson 4 of 8
Databases and data

Postgres backup and restore with pg_dump and pg_restore

pg_dump writes a consistent copy of one database to a file, and pg_restore or psql loads that file into a database, so you can back up, move or rebuild Postgres data.

By the end you will

Dump a database in custom format, restore it into a scratch database, and confirm the row counts match.

Time
25 min
Level
Intermediate
Check
4 questions
You need
  • A running Postgres with a database to dump
  • Enough free disk space for the dump file

Use pg_dump -Fc to write a compressed, consistent copy of a database, pg_dumpall --globals-only for the roles, and pg_restore to load the copy into an empty database. A backup only counts once you have restored it somewhere and compared the data, so this lesson ends with that check. It goes deeper than back up a Postgres database in Docker and test a backup by restoring it, which cover the Docker and cron side.

How it works#

pg_dump connects like any client, opens one transaction with a snapshot, and reads the schema and data as they were at that moment. Writers are not blocked. It supports four output formats:

FlagFormatRestore with
-Fp (default)Plain SQL textpsql
-FcCustom, compressedpg_restore
-FdDirectory of filespg_restore, supports -j on dump and restore
-FtTarpg_restore

Custom format is the usual choice: it is compressed and pg_restore can list contents, restore single tables, and run restore jobs in parallel. Plain SQL is easy to read and diff, and it can be loaded anywhere psql works. The pg_dump tool saves one database only. Roles, which are cluster-wide, need pg_dumpall --globals-only.

Step 1: Dump a database#

Run these as a role that can read everything in the database. On an apt install:

bash
sudo -u postgres pg_dump -Fc shop -f /var/backups/shop-$(date +%F).dump

Over TCP with a password from the environment:

bash
PGPASSWORD=change-me pg_dump -h 127.0.0.1 -U app -Fc shop -f shop.dump

-f names the output file, so no shell redirect is needed. Check the size with ls -lh. An empty or tiny file means the dump failed. In Docker, run it inside the container and write on the host:

bash
docker exec pg pg_dump -U postgres -Fc shop > shop.dump

Do not add -t (a TTY) to docker exec when redirecting output, because it can corrupt the binary dump.

For plain SQL, drop -Fc and add -f shop.sql. For a directory dump that can restore in parallel: pg_dump -Fd -j 4 shop -f shop.dir.

Step 2: Save roles with pg_dumpall#

bash
sudo -u postgres pg_dumpall --globals-only > globals.sql

The file contains CREATE ROLE statements, including password hashes, so treat it as a secret: restrict it with chmod 600 and store it encrypted. Without it, a restore onto a fresh server fails with role "app" does not exist when ownership statements run.

Step 3: Restore into a scratch database#

Do this first, never straight over production. Create an empty database and load the dump:

bash
sudo -u postgres createdb shop_check
sudo -u postgres pg_restore -d shop_check --no-owner --exit-on-error shop.dump

--no-owner skips ALTER ... OWNER TO statements, which avoids errors when the original roles are missing. Use -j 4 to restore with four parallel jobs (custom or directory format only). A plain SQL dump loads with psql -d shop_check -f shop.sql, and adding -v ON_ERROR_STOP=1 stops at the first error instead of printing errors and continuing.

Step 4: Compare counts#

bash
sudo -u postgres psql -d shop -c "SELECT count(*) FROM orders;"
sudo -u postgres psql -d shop_check -c "SELECT count(*) FROM orders;"

Compare a few big tables, and check the newest row with something like SELECT max(created_at) FROM orders;. The counts match only if no writes happened since the dump, so compare against a quiet moment or expect a small difference. When done, remove the scratch copy with dropdb shop_check. Double check the name: DROP DATABASE and dropdb delete data permanently with no confirmation.

Step 5: Restore over an existing database#

Only do this when you mean to overwrite it, after a fresh backup of the current state:

bash
pg_restore -d shop --clean --if-exists --no-owner shop.dump

--clean drops each object before recreating it, and --if-exists suppresses errors for objects that are absent. This destroys current data in those tables. Stop the app first so no writes happen in the middle of the restore. To rebuild from nothing, create the roles from globals.sql with psql -f globals.sql, then createdb -O app shop, then pg_restore.

Check it worked#

  • pg_restore -l shop.dump | head prints a table of contents, which proves the file is a readable archive.
  • The scratch database has the same tables (\dt) and similar row counts.
  • The restore command exited with status 0: run echo $? right after it.
  • The dump file is not zero bytes and is copied off the server (see the backup and restore terms).

Edge cases and gotchas#

  • Version rule. Use a pg_dump at least as new as the server you dump. A newer pg_dump can read older servers, while an older one refuses a newer server with server version: ...; pg_dump version: .... Restore into the same or a newer major version.
  • Extensions must exist. If the dump uses an extension such as pg_trgm, install its package on the target before restoring, or CREATE EXTENSION fails.
  • Large objects and sequences. Both are included by default in a full-database dump. A partial dump with -t may skip related objects, so test it.
  • Dumps are logical, not byte copies. Restore rebuilds indexes, which can take time on big tables. Plan for it.
  • Disk space. Check df -h before dumping. See fix a full disk when the backup directory fills up.
  • Backups beside the data are not backups. Copy dumps to another machine as well, as the 3-2-1 rule says.

Troubleshooting#

SymptomLikely causeFix
pg_dump: error: connection to server on socket ... failed: FATAL: role "root" does not existRunning as your Linux userUse sudo -u postgres pg_dump ... or pass -U
pg_dump: error: aborting because of server version mismatchpg_dump is older than the serverInstall a matching or newer client
pg_restore: error: could not execute query: ERROR: role "app" does not existRoles not created yetLoad globals.sql first or use --no-owner
pg_restore: error: input file appears to be a text format dump. Please use psql.Dump was plain SQLpsql -d shop_check -f shop.sql
ERROR: relation "orders" already existsRestoring into a non-empty databaseUse a fresh database or --clean --if-exists
pg_dump: error: query failed: ERROR: permission denied for table ordersRole cannot read all tablesDump as the owner or a superuser
pg_restore: error: unsupported version (1.15) in file headerRestoring with an older pg_restoreUse pg_restore from the newer version
ERROR: database "shop_check" is being accessed by other usersOpen connections block dropDisconnect clients, then retry dropdb
could not open extension control file ".../pg_trgm.control"Extension package missingInstall the contrib package

Quick reference#

bash
pg_dump -Fc shop -f shop.dump
pg_dump -Fd -j 4 shop -f shop.dir
pg_dumpall --globals-only > globals.sql
createdb shop_check
pg_restore -d shop_check --no-owner -j 4 shop.dump
pg_restore -d shop --clean --if-exists shop.dump   # overwrites data
pg_restore -l shop.dump
dropdb shop_check                                  # permanent

Next#

Continue with upgrade Postgres to a new major version, which relies on exactly these tools.

Check what you learned4 questions
1Which flag makes pg_dump write the compressed custom format?
2You run pg_restore --clean --if-exists -d shop file.dump against a live database. What happens?
3Where do roles and their passwords get saved?
4Why restore into a new scratch database instead of the live one?

Frequently asked questions

What is the difference between pg_dump custom format and plain SQL?

Plain format is a text SQL script you load with psql. Custom format (-Fc) is compressed, lets pg_restore pick which objects to restore, and supports parallel restore with -j.

Does pg_dump back up roles and users?

No. Roles are cluster-wide, so pg_dump leaves them out. Save them with pg_dumpall --globals-only.

Does pg_dump lock the database?

It runs in a single consistent snapshot and takes only light locks, so reads and writes continue. A long dump can still block schema changes such as ALTER TABLE.

Can I restore a dump into a different Postgres version?

Usually yes into the same or a newer major version. Use pg_dump from the newer version against the older server when you migrate, and test the restore first.

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