How to Back Up PostgreSQL with pg_dump and Point-in-Time Recovery Basics

PostgreSQL stores your data in a way that makes simple file copies unreliable as backups. The database files change while the server runs, so copying them by hand can produce a set you cannot start. The supported route is pg_dump, a tool that reads the database through the server itself and writes a consistent snapshot. This postgresql backup with pg_dump guide shows what point-in-time recovery actually requires, so you can restore to last night, or to a minute before a bad delete.

pg_dump ships with PostgreSQL, so if the server is installed, the tool is already there. It connects like any client, asks the server for the database contents in a consistent state, and writes the result to a file. That file is a complete, logical copy of the database: tables, data, indexes, and settings. Feed it to a fresh PostgreSQL server and you get the same database back. It is the simplest reliable backup method for the small databases a VPS usually runs.

PostgreSQL Backup with pg_dump: The Basic Commands

The simplest form is pg_dump -U postgres your_database > backup.sql. That writes a plain SQL dump you can read and restore with psql. Add the custom format flag, -Fc, and the dump becomes a compressed archive that restores faster and lets you pick which tables to restore. For most small servers, the custom format is the better default: pg_dump -U postgres -Fc your_database > backup.dump. Restore it with pg_restore instead of psql.

To back up every database on the server, use pg_dumpall. It dumps all databases plus the global objects that pg_dump skips, such as roles and tablespace definitions. A pg_dump backup postgres owners rely on for full-server recovery usually pairs a pg_dumpall for the globals with a per-database pg_dump in custom format. The per-database dumps restore faster and let you restore one app without touching the others, while pg_dumpall covers the roles those databases need.

Automating pg_dump with Cron

A backup you run by hand is a backup you will forget, so schedule it. A small shell script that runs pg_dump for each database, names the file with the date, and deletes files older than your retention window is all you need. Schedule it with cron at a quiet hour, such as 2 a.m., and send the output to a log file you check weekly. A cron job that fails silently is worse than no job, because it creates confidence you have not earned.

The postgres user needs a way to authenticate without a password prompt. The standard answer is a .pgpass file in the postgres home directory, owned by postgres with permissions 600, holding the host, database, user, and password. Cron running as the postgres user reads that file automatically. Never put the password in the crontab or in the script itself, and never use the superuser password for routine backups if a limited backup role can do the job.

Keep retention simple at first: fourteen daily dumps and four weekly dumps covers the restores you will actually need. Let the script delete older files itself with find and -mtime. If the database grows, watch the disk. A dump of a busy app database grows every week, and a retention policy that fit in January can fill the disk by June. Check dump sizes monthly with ls -lh and adjust the retention window before the disk forces the issue.

Point-in-Time Recovery Basics: What pg_dump Cannot Do

A nightly pg_dump restores you to last night. If someone deletes a table at 3 p.m., you lose everything since the last dump. Point-in-time recovery, or PITR, closes that gap. PostgreSQL can replay its write-ahead log, the WAL, to rebuild the database at any moment between backups. That is the difference between losing a day of data and losing a few minutes.

A postgresql point-in-time recovery setup needs two ingredients. The first is a base backup, a physical copy of the whole data directory taken with pg_basebackup while the server runs. The second is WAL archiving: PostgreSQL writes every change to WAL files, and with archive_mode on and an archive_command configured, it copies each finished WAL file to a safe location as soon as it fills up. Together, the base backup plus the archived WAL files let you restore to any point in time. Without WAL archiving, there is no point-in-time recovery, only nightly dumps.

Setting up WAL archiving takes a few configuration changes and a restart, so do it during a maintenance window. Set wal_level to replica, turn archive_mode on, and point archive_command at a script that copies WAL files to your backup location, testing that the command returns success only when the copy actually lands. A failing archive_command that reports success is how people discover, months later, that their WAL archive has gaps and their recovery point does not exist. Those are the postgres wal archiving basics: a base backup, an archive command, and a test. Test the archive by forcing a WAL switch and confirming the file appears in the archive location.

Testing a PostgreSQL Restore

Test every backup by restoring it somewhere it cannot hurt anything. Create a scratch database and restore the dump into it with pg_restore, then check table counts and a few rows you know. For a plain-format dump, feed it to psql instead. The restore test proves the dump is valid and that you remember the command, and it takes only a few minutes for a small database.

Test PITR the same way, once, on a spare server or a local machine. Restore the base backup, replay the WAL files to a chosen time, and confirm the database comes up at that point. This is the test most people skip, and it is the one that matters most, because PITR has more moving parts than a plain dump: the base backup, the archive, the recovery settings, and the target time all have to agree. A recovery you have practised once is a recovery you can run calmly when the site is down.

Offsite Copies and Retention

A dump on the same disk protects you against a bad query or a deleted table. It does nothing if the disk dies. Copy the dumps and the WAL archive to a second location as part of the same script, and confirm the copy lands before the local cleanup deletes old files. A second cheap VPS, an object storage bucket, or a NAS at home all work. The 3-2-1 backup rule for servers explains the shape: three copies, two different media, one offsite.

Retention for PITR is different from retention for dumps. WAL files accumulate constantly, so the archive grows every day. Keep enough WAL to cover the time between base backups, and take a fresh base backup weekly so old WAL files can be deleted. A base backup every Sunday plus WAL archiving gives you a full week of point-in-time recovery with a bounded archive size. If you skip the weekly base backup, the archive grows without limit and the disk fills up.

PostgreSQL also benefits from the same file-level backup thinking as the rest of the server. The database dumps cover the data, but the configuration in /etc/postgresql, the application files, and the uploads still need their own backup. The rsync backup tutorial for a second VPS covers the file side, and the Restic tutorial for encrypted backups to S3-compatible storage shows how to push those files offsite with encryption.

Common PostgreSQL Backup Mistakes

The most common mistake is assuming a file copy of the data directory is a backup. It is not, unless the server was stopped cleanly first, and even then a restore is fragile. The second mistake is turning on WAL archiving but never testing a recovery, so the archive has gaps nobody notices. The third is backing up the database and forgetting the roles: a pg_dump of one database does not include the login roles, so a restore onto a fresh server fails until you recreate them. pg_dumpall covers that gap, which is why it belongs in the routine even when per-database dumps do the daily work.

The fourth mistake is running backups as the superuser with the password in the script. A dedicated backup role with read-only access to the databases is enough for pg_dump, and a .pgpass file with tight permissions keeps the credential out of the process list. The fifth mistake is never checking the logs. A postgres wal archiving setup that stops working quietly is a recovery plan that evaporates one WAL file at a time. Check the archive weekly: confirm new WAL files arrive, confirm the newest dump restores, and confirm the disk has room for another week.

Start with the nightly pg_dump tonight, add WAL archiving when you have a maintenance window, and test a restore this week. A nightly dump plus a practised point-in-time recovery is a backup plan a small VPS can actually deliver, and it uses tools that are already installed.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.