Chapter 4 · Lesson 5 of 18
Deploy and operate

Backups and the 3-2-1 rule

The 3-2-1 rule means keeping three copies of your data, on two kinds of storage, with one copy stored offsite.

By the end you will

Make a Postgres dump and a volume archive, and plan a 3-2-1 backup with a tested restore.

Time
20 min
Level
Beginner
Check
4 questions
You need
  • A running Docker Compose app with a Postgres service
  • A second place to store copies

The 3-2-1 backup rule

The 3-2-1 rule: keep three copies of your data, on two different kinds of storage, with one copy off-site, so no single failure loses everything.
  1. Back up your data to a second kind of media, such as another disk.
  2. Send one more copy to a different place, so a single disaster cannot take everything.
  3. That makes three copies in total, on two kinds of media, with one offsite.
  4. Now pull a backup back down onto a spare machine.
  5. A backup only counts once you have restored from it successfully.
Static diagram
  1. Live datadump and copySecond disk
  2. Live datasend awayOffsite storage
  3. Second disksyncOffsite storage
  4. Offsite storagefetchRestore test
  5. Restore testit worksLive data

A server disk dies, a bad migration drops a table, or someone deletes the wrong folder. In every case the only thing that saves you is a copy you can restore from, kept somewhere the problem did not reach. The 3-2-1 rule is a simple plan for that.

How it works#

The rule has three numbers:

  • 3 copies of your data: the live data plus two backups.
  • 2 different media: for example the server disk and a separate storage service. One failure type, such as a broken disk model, should not hit both.
  • 1 copy offsite: in another location or account, so a fire, theft, billing lock or hacked login does not take everything.

There are two common ways to copy data from a Docker app. A logical backup (pg_dump) asks Postgres to write out its contents as SQL. Postgres gives you a consistent view even while the app keeps writing. The dump starts a transaction, reads every table as it was at that moment, and writes SQL statements that rebuild the data. A file-level backup (archiving a volume) copies the raw files. That is only safe for data that is not changing, or when the service is stopped. For databases, prefer the logical dump.

A backup has three parts you must plan: how it is made, where it is stored, and how it is restored. Only the last one proves the first two worked.

Step 1: Dump a Postgres database#

Run this from the host while the database container is up (replace names with yours):

bash
docker compose exec -T db pg_dump -U app app > backup-$(date +%F).sql

-T turns off the pseudo-terminal, so Docker does not add terminal characters to the file. -U app is the database user, and the last app is the database name. The > writes to a file on the host, not inside the container.

What you should see: no output, and a new backup-YYYY-MM-DD.sql file whose size is more than zero.

pg_dump saves one database. It does not include roles (users) or other databases. See Back up a Postgres database in Docker for globals and the custom format.

Step 2: Archive a volume#

For files such as uploads, archive the volume with a temporary container. Stop writes first if you can.

bash
docker run --rm -v app_data:/data -v "$PWD":/backup alpine \
  tar czf /backup/app_data-$(date +%F).tar.gz -C /data .

--rm removes the helper container afterwards. -v app_data:/data mounts the volume. The second -v mounts your current folder so the archive lands on the host. -C /data . archives the contents of the volume without a leading path. List volume names with docker volume ls; Compose usually prefixes them with the project name.

What you should see: no output, and an app_data-YYYY-MM-DD.tar.gz file in the current folder.

Step 3: Copy it away#

Copy the files to a second disk or storage service, and one more copy to a different location. Use a tool you trust, such as rsync over SSH:

bash
rsync -av backup-*.sql user@203.0.113.20:/srv/backups/

What you should see: the file names listed, then a short transfer summary. Run the command a second time and it should transfer nothing new.

Step 4: Test a restore#

Warning: restoring into your live database overwrites or conflicts with data. Test in a scratch database or a separate machine first.

bash
docker compose exec db createdb -U app scratch
docker compose exec -T db psql -U app -d scratch < backup-2026-11-27.sql

What you should see: a stream of SET, CREATE TABLE and COPY lines from psql, and no lines starting with ERROR.

Check it worked#

  • The dump file is not empty (ls -lh shows a real size).
  • tar tzf app_data-2026-11-27.tar.gz | head lists your files.
  • After the test restore, docker compose exec db psql -U app -d scratch -c '\dt' lists your tables, and a SELECT count(*) on one of them returns a number you expect.
  • The offsite copy exists: list it on the other machine.

Edge cases and gotchas#

  • A copy of the live data directory is not a safe backup. The files change while you copy, so Postgres may refuse to start from them. Use pg_dump, or stop the container first.
  • An empty or tiny dump can still be “successful”. If the shell redirect works but pg_dump fails, you get a zero-byte file and an error on screen that nobody reads in a cron job. Check the exit code and the file size in any script.
  • Backups on the same disk die with the disk. A backup folder under /var/lib/docker or next to the app counts as the same medium as the data.
  • Backups contain secrets. A dump holds password hashes and personal data. Restrict permissions with chmod 600 and encrypt anything that leaves the server.
  • The date in the file name depends on the server clock and time zone. If the clock drifts, you can overwrite yesterday’s file or sort backups wrongly.
  • Retention fills the disk. One dump a day with no cleanup eventually fills the disk and breaks the app. Decide how many to keep and delete the rest.
  • Provider snapshots are not a full plan. They usually sit in the same account as the server, so a locked account loses both.

Troubleshooting#

SymptomLikely causeFix
Dump file is 0 bytesWrong container, user or database nameRun the command without the redirect and read the error
role "postgres" does not existYour database user is not postgresUse the user from your compose file, for example -U app
database "scratch" does not existYou skipped createdbCreate it first with createdb -U app scratch
Restore prints already exists errorsYou restored into a database that has tablesRestore into a fresh, empty database
Garbled characters in the dumpYou ran without -T and a TTY was attachedAdd -T to docker compose exec
tar archive is emptyWrong volume name, so an empty new volume was mountedCheck docker volume ls and use the exact name
rsync: connection unexpectedly closedSSH login to the target failedTest ssh user@203.0.113.20 by hand first
pg_dump: error: connection to server failedThe database container is not up or the service name is wrongRun docker compose ps and use the service name from your compose file
Backup job runs but nobody notices it failingNo check on exit code or file sizeMake the script exit on error and alert when the file is missing or tiny

Real-world scenario#

A small shop runs one app and a Postgres container on a single server. A developer ships a migration that drops a column the checkout still uses. Orders start failing, and the fix needs the old data back.

The team has a nightly dump from 03:00 and a copy on a storage service. They create a scratch database, restore last night’s dump into it, and read the column from there:

bash
docker compose exec db createdb -U app scratch
docker compose exec -T db psql -U app -d scratch < backup-2026-11-27.sql
docker compose exec db psql -U app -d scratch -c 'SELECT id, discount_code FROM orders LIMIT 5;'

They copy the lost values back into the live table with a normal UPDATE, and the checkout works again. They lose only the orders from after 03:00, which is the cost of a nightly schedule. Afterwards they move the dump to every six hours.

Quick reference#

TaskCommand
Dump one databasedocker compose exec -T db pg_dump -U app app > backup.sql
Archive a volumedocker run --rm -v VOL:/data -v "$PWD":/backup alpine tar czf /backup/VOL.tar.gz -C /data .
List an archivetar tzf VOL.tar.gz | head
Copy offsitersync -av backup-*.sql user@203.0.113.20:/srv/backups/
Test restorecreatedb scratch, then psql -d scratch < backup.sql
The rule3 copies, 2 media, 1 offsite

Security and safety notes#

  • Never restore a test dump into the live database.
  • Do not delete the old backup until the new one has been restored at least once.
  • Keep at least one copy where a hacked server cannot delete it.

Next#

Know when something breaks: Monitor uptime simply.

Check what you learned4 questions
1What does the 3-2-1 rule ask for?
2Why is a backup copy on the same server only a partial backup?
3Where should you first try a restore?
4Why is copying a running Postgres data directory a poor backup?

Frequently asked questions

Is a copy on the same server a backup?

Only partly. It helps against deleted files but not against a failed disk or a hacked server. That is why one copy should live offsite.

How often should I test a restore?

Whenever you change how backups work, and then on a regular schedule you can keep up with. A backup you have never restored is only a guess.

Can I just copy the Postgres data directory while the database runs?

No. Files change while you copy them, so the result can be inconsistent and fail to start. Use pg_dump, or stop the database first and then copy.

Does a provider snapshot of my server count as a backup?

It counts as one copy, but it usually lives in the same account and region as the server. Keep another copy somewhere that an account lockout cannot reach.

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