Chapter 4 · Lesson 12 of 18
Deploy and operate

Test a backup by restoring it

A backup only counts once you have restored it somewhere safe and checked the data, so test restores go into a separate throwaway database.

By the end you will

Restore a Postgres backup into a throwaway container and compare row counts with the original.

Time
25 min
Level
Intermediate
Check
4 questions
You need
  • A backup file from pg_dump
  • Docker installed on a machine that is not production

To test a backup, start a throwaway Postgres container, restore the file into an empty database there, and compare a few row counts with production. If the counts match and the app can read the data, the backup works. Until then it is only a file.

Warning: never run these commands against your production container. The restore target below is a new, disposable container.

How it works#

A restore replays the dump into a server. For a plain SQL file, psql reads the statements one by one: CREATE TABLE, then COPY to load rows, then indexes and constraints. For a custom-format file, pg_restore reads the archive and does the same work, with options to pick tables or skip owners.

The test is valuable because it checks things a file listing cannot: the file is complete, the Postgres version accepts it, the roles it refers to exist, and the data is usable. The target must be empty and separate from production, since a dump creates objects and a populated database will answer with already exists errors.

A worked example: your nightly job wrote backup.dump with -Fc. You start a Postgres of the same major version as production, create an empty database DBNAME, run pg_restore, then run a SELECT count(*) on your biggest table. You compare that number with production at the dump time. That is the whole test, and it takes a few minutes.

Step 1: Start a throwaway Postgres#

Use the same major version as production:

bash
docker run -d --name restore-test -e POSTGRES_PASSWORD=testonly postgres:16

-d runs it in the background, --name names it so you can remove it later, and -e sets the required password. Change 16 to match your version. There is no -p, so nothing is published to the network.

What you should see: a long container ID. docker ps lists restore-test as Up. Wait a few seconds before the next step, because Postgres needs time to initialize.

Step 2: Create an empty database#

bash
docker exec restore-test createdb -U postgres DBNAME

What you should see: no output. If you see could not connect to server, wait a little and retry.

Step 3: Restore the backup#

For a plain SQL file:

bash
docker exec -i restore-test psql -U postgres -d DBNAME < backup.sql

-i keeps standard input open so the redirected file reaches psql. For a gzip file, use gunzip -c backup.sql.gz | docker exec -i restore-test psql -U postgres -d DBNAME.

For a custom format (-Fc) file:

bash
docker exec -i restore-test pg_restore -U postgres -d DBNAME --no-owner < backup.dump

--no-owner skips setting the original owner, which would fail if that role does not exist here.

What you should see: for plain SQL, a stream of SET, CREATE TABLE, COPY and CREATE INDEX lines. For pg_restore, usually no output at all. Any line starting with ERROR needs a look.

Step 4: Compare the data#

Count rows in an important table and compare with production:

bash
docker exec restore-test psql -U postgres -d DBNAME -c "SELECT count(*) FROM users;"

Replace users with one of your tables. The count should match production at the time of the dump, or be slightly lower if new rows arrived since. Also run \dt in psql to confirm the tables exist:

bash
docker exec restore-test psql -U postgres -d DBNAME -c '\dt'

What you should see: a table with a count column and one number, then a list of your tables.

Step 5: Clean up#

The next command deletes the throwaway container and its data. It only touches restore-test:

bash
docker rm -f restore-test

What you should see: the name restore-test printed back.

Check it worked#

The restore passes when all of these hold: no unexplained ERROR lines, the tables listed by \dt match what you expect, row counts for two or three key tables match production at the dump time, and one known record (a recent order, a specific user) is present. Write down the date and the file name that you tested.

Edge cases and gotchas#

  • Version differences. A dump from a newer Postgres major version may not load into an older one. Test with the same version as production.
  • Missing roles. A single-database dump does not include roles. Restore globals.sql first, or use --no-owner, and make sure grants are checked in your real recovery plan.
  • Extensions. If the app uses an extension, the test image must provide it. Otherwise you see an error such as extension "NAME" is not available.
  • Errors you can ignore and errors you cannot. A few warnings about ownership may be harmless. Missing tables or failed COPY commands are not.
  • Restoring a partly filled database. If a first attempt half-worked, remove the container and start again rather than retrying on top.
  • Disk space on the test machine. A restored database can be larger than the compressed file. Check df -h first.
  • Timing matters for real recovery. Time the restore. A restore that takes three hours is something you should know before an outage.
  • Running the test on production by accident. Check the container name in every docker exec command before you press Enter.

Troubleshooting#

SymptomLikely causeFix
psql: error: connection to server ... failedPostgres is still startingWait a few seconds and retry
role "USER" does not existThe dump refers to the original ownerUse --no-owner with pg_restore, or create the role
Many already exists errorsTarget database is not emptyRemove the container and start fresh
pg_restore: error: input file appears to be a text format dumpA plain SQL file was given to pg_restoreUse psql for plain files
A flood of odd errors that mention \N or invalid commandsA COPY failed earlier and its data lines are read as commandsFix the first ERROR and restore again
database "DBNAME" does not existcreatedb step skippedRun Step 2
extension "NAME" is not availableThe image lacks the extensionUse an image that includes it
Counts differ from productionRows arrived after the dump, or the restore partly failedCompare at the dump time and recheck errors
Restore is very slowBig data or small diskTest on a machine sized like production

Real-world scenario#

A team has dumped nightly for months. Before a major upgrade they finally run a restore test. The plain dump loads, but halfway through they see ERROR: role "app_readonly" does not exist. The dump had grants for a role that lives only on the old server, and a single-database dump never included it.

They add a nightly pg_dumpall -g to the job, restore globals.sql before the database, and run the test again. This time the log has no errors, \dt lists every table, and the order count matches production within a few rows. They note the restore took eleven minutes, so they know what a real recovery will cost, and they put a calendar reminder to repeat the test every quarter.

Quick reference#

StepCommand
Start scratch serverdocker run -d --name restore-test -e POSTGRES_PASSWORD=testonly postgres:16
Empty databasedocker exec restore-test createdb -U postgres DBNAME
Restore plaindocker exec -i restore-test psql -U postgres -d DBNAME < backup.sql
Restore customdocker exec -i restore-test pg_restore -U postgres -d DBNAME --no-owner < backup.dump
Count rowsdocker exec restore-test psql -U postgres -d DBNAME -c "SELECT count(*) FROM users;"
Removedocker rm -f restore-test

Security and safety notes#

  • Do not publish the throwaway container’s port. It uses a weak password on purpose and holds real data.
  • Delete the container and the dump copy on the test machine when you finish.
  • Never point restore commands at the production container name.

Next#

Put the app itself on a server: Deploy an app with Docker Compose on a server.

Check what you learned4 questions
1Where should a test restore go?
2How do you restore a custom format (-Fc) dump?
3You see many already exists errors during restore. What happened?
4A restore finishes with no errors, but a feature still breaks on the restored data. What is a likely gap?

Frequently asked questions

How often should I test a restore?

After you first set up backups, after any change to the backup method, and then on a regular schedule you will actually keep.

Can I restore into my live database to test?

No. Restoring over production can overwrite or duplicate real data. Always use a separate container or database.

Why does pg_restore say role does not exist?

The dump refers to the original owner role, which is missing on the test server. Use --no-owner, or create the role first.

How do I know the restored data is complete?

Compare row counts of important tables with production, and check a few known rows. Matching counts at dump time are a good sign, not a proof.

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