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

URL: https://levelrail.com/learn/databases/postgres-backup-and-restore-with-pg-dump/
Updated: 2026-11-27

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](https://levelrail.com/learn/deploy-operate/back-up-a-postgres-database-in-docker/)) and [test a backup by restoring it](https://levelrail.com/learn/deploy-operate/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:

| Flag | Format | Restore with |
| --- | --- | --- |
| `-Fp` (default) | Plain SQL text | `psql` |
| `-Fc` | Custom, compressed | `pg_restore` |
| `-Fd` | Directory of files | `pg_restore`, supports `-j` on dump and restore |
| `-Ft` | Tar | `pg_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](https://levelrail.com/learn/glossary/#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](https://levelrail.com/learn/glossary/#backup)) and [restore](https://levelrail.com/learn/glossary/#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](https://levelrail.com/learn/troubleshooting/fix-a-full-disk-on-a-linux-server/)) 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](https://levelrail.com/learn/deploy-operate/backups-and-the-3-2-1-rule/)) says.

## Troubleshooting

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `pg_dump: error: connection to server on socket ... failed: FATAL:  role "root" does not exist` | Running as your Linux user | Use `sudo -u postgres pg_dump ...` or pass `-U` |
| `pg_dump: error: aborting because of server version mismatch` | pg_dump is older than the server | Install a matching or newer client |
| `pg_restore: error: could not execute query: ERROR:  role "app" does not exist` | Roles not created yet | Load `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 SQL | `psql -d shop_check -f shop.sql` |
| `ERROR:  relation "orders" already exists` | Restoring into a non-empty database | Use a fresh database or `--clean --if-exists` |
| `pg_dump: error: query failed: ERROR:  permission denied for table orders` | Role cannot read all tables | Dump as the owner or a superuser |
| `pg_restore: error: unsupported version (1.15) in file header` | Restoring with an older pg_restore | Use pg_restore from the newer version |
| `ERROR:  database "shop_check" is being accessed by other users` | Open connections block drop | Disconnect clients, then retry `dropdb` |
| `could not open extension control file ".../pg_trgm.control"` | Extension package missing | Install 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
```

## Related lessons

- [Back up a Postgres database in Docker](https://levelrail.com/learn/deploy-operate/back-up-a-postgres-database-in-docker/)): the container and cron version of this.
- [Test a backup by restoring it](https://levelrail.com/learn/deploy-operate/test-a-backup-by-restoring-it/)): the habit that makes backups real.
- [Backups and the 3-2-1 rule](https://levelrail.com/learn/deploy-operate/backups-and-the-3-2-1-rule/)): where copies should live.
- [Postgres roles and permissions](https://levelrail.com/learn/databases/postgres-roles-and-permissions/)): the roles that pg_dumpall --globals-only saves.
- [Install Postgres and connect with psql](https://levelrail.com/learn/databases/install-postgres-and-connect-with-psql/)): the psql session you use to check a restore.
- [Self-hosted Postgres in Docker, connect your app](https://levelrail.com/blog/self-hosted-postgres-docker-connect-app/)): the setup these dumps protect.
- [Upgrade Postgres to a new major version](https://levelrail.com/learn/databases/upgrade-postgres-major-version/)): reuse the dump and restore method.

## Next

Continue with [upgrade Postgres to a new major version](https://levelrail.com/learn/databases/upgrade-postgres-major-version/)), which relies on exactly these tools.

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

- [PostgreSQL documentation, pg_dump](https://www.postgresql.org/docs/current/app-pgdump.html)
- [PostgreSQL documentation, pg_restore](https://www.postgresql.org/docs/current/app-pgrestore.html)
- [PostgreSQL documentation, pg_dumpall](https://www.postgresql.org/docs/current/app-pg-dumpall.html)
