Portabase Logo
Portabase AgentDatabases

PostgreSQL

Specific configuration for PostgreSQL.

Add this database from the dashboard

Since Dashboard 1.29.0 and Agent 1.19.0, you can add this database directly from the dashboard (Add database on the agent page), without editing any file. See Adding a Database. The settings described below also apply to the dashboard form.

PostgreSQL is fully supported by the Portabase agent. We use native pg_dump tools to ensure consistent and reliable backups.

Two modes are available:

  • postgresql: Single database backup using pg_dump. Targets one specific database.
  • postgresql-cluster: Full cluster backup using pg_dumpall. Dumps every database in the instance plus global objects (roles, ownership, grants, tablespaces). Useful when advanced roles and ownership are configured at the cluster level. Large clusters can use physical incremental backups instead.

Configuration

When running portabase agent db add, select postgresql as the database type.

Specific parameters asked:

  • Database Name: The exact name of the database to backup (e.g., app_db). Unlike other engines, you must target a specific database.

Options

The following optional fields can be set under an options key in the database configuration.

OptionTypeDefaultDescription
keep_ownershipbooleanfalseWhen true, omits --no-owner and --no-privileges from the dump. Ownership and role assignments are preserved in the output. By default these flags are applied, keeping restores portable across different users and environments, for example, when migrating from one database instance to another.
clean_modestring"clean"Controls how the target database is cleaned before a restore. One of none, clean, drop_schemas, drop_database. See Clean mode below.
exclude_tablesstring[][]Tables to leave out of the dump, one pg_dump pattern per entry (--exclude-table). See Excluding tables and schemas below.
exclude_schemasstring[][]Schemas to leave out of the dump, one pg_dump pattern per entry (--exclude-schema). See Excluding tables and schemas below.
databases.json (with options)
{
  "name": "Database - PostgreSQL",
  "type": "postgresql",
  "host": "postgres",
  "port": 5432,
  "username": "postgres",
  "password": "mysecretpassword",
  "database": "app_db",
  "generated_id": "...",
  "options": {
    "keep_ownership": true,
    "clean_mode": "drop_schemas"
  }
}

Clean mode

pg_restore --clean only drops objects that exist in the backup's own table of contents. Anything already present in the target that the dump does not know about survives and can collide with the restore, so restoring into a populated database can partially fail (already exists, constraint or key errors). clean_mode lets you guarantee a clean target before restoring.

ValueBehaviourUse case
noneNo pre-clean and no --clean.Restore into a known-empty database. Fastest, least destructive.
cleanCurrent behaviour: pg_restore --clean --if-exists. Default.Existing setups. Not a full reset (see above).
drop_schemasDrops every non-system schema CASCADE, then restores.Recommended for new setups. Works on managed Postgres (RDS, Cloud SQL, Neon, Supabase) where the role cannot drop the database.
drop_databaseDROP DATABASE + CREATE DATABASE preserving encoding, collation and owner, then restores.Full reset on self-hosted Postgres where the role has CREATEDB + ownership, or is superuser.

If the value is absent or unrecognized, the agent falls back to clean. drop_database is never applied by default.

drop_schemas and drop_database are destructive and have no rollback. If the agent stops between the drop and the restore, the target is left empty or gone. drop_database additionally requires that the connecting role is the database owner and holds CREATEDB, or is a superuser, otherwise the restore fails a preflight check before anything is dropped. Prefer drop_schemas on managed providers where you cannot drop the database.

drop_schemas is schema-scoped: it does not remove database- or cluster-scoped objects (event triggers, publications/subscriptions, database-level settings, roles, tablespaces). Extensions installed into a dropped schema are recreated on restore only if the restoring role has permission (superuser-only extensions such as pg_stat_statements are not). For a fully pristine target including global objects, use drop_database.

databases.json (drop and recreate before restore)
{
  "name": "Database - PostgreSQL",
  "type": "postgresql",
  "host": "postgres",
  "port": 5432,
  "username": "postgres",
  "password": "mysecretpassword",
  "database": "app_db",
  "generated_id": "...",
  "options": {
    "clean_mode": "drop_database"
  }
}

Excluding tables and schemas

Since Agent 1.23.0 and Dashboard 1.33.0

Older agents ignore these options and dump everything.

pg_dump stops at the first table the backup user cannot read, so a single table without grants makes the whole backup fail with permission denied for table …. Some applications create such tables: Metabase, for example, creates search_index__* tables that do not inherit the grants of the other tables. Rather than backing up with the database owner, leave those objects out of the dump:

databases.json (skip Metabase search index tables)
{
  "name": "Database - Metabase",
  "type": "postgresql",
  "host": "postgres",
  "port": 5432,
  "username": "backup",
  "password": "mysecretpassword",
  "database": "metabase",
  "generated_id": "...",
  "options": {
    "exclude_tables": ["public.search_index__*"],
    "exclude_schemas": ["metabase_tmp"]
  }
}

Each entry is a pg_dump pattern, passed as one --exclude-table=<pattern> or --exclude-schema=<pattern> argument: * and ? are wildcards, schema.table qualifies a name, and double quotes keep upper-case names ("MyTable"). Blank entries are ignored. In the dashboard form, enter one pattern per line; with the CLI, separate them with commas (-o exclude_tables=public.search_index__*,audit.tmp_*). The backup job log lists what was excluded, and a value that is not a list is ignored with a warning.

Excluded objects are not in the backup. With clean_mode clean (default) or none, the ones already in the restore target are left untouched. With drop_schemas or drop_database, they are dropped and not recreated.

These options apply to postgresql only: pg_dumpall (cluster mode) has no table or schema exclusion.

Cluster Backup (pg_dumpall)

Use the cluster mode when you need to back up the entire instance: all databases together with global objects such as roles, ownership and grants. This is the recommended choice when advanced roles and ownership are configured at the database cluster level, since a single pg_dump does not capture cluster-wide global objects.

User specified in the configuration must be a superadmin for pg_dumpall to dump all databases and global objects.

When running portabase agent db add, select postgresql-cluster as the database type.

Specific parameters asked:

  • Database Name: The exact name of the database to backup (e.g., app_db). Unlike other engines, you must target a specific database.

Cluster backups can be significantly larger and slower than single-database backups, since every database in the instance is included. Restoring a pg_dumpall output recreates roles and ownership globally.

Physical incremental backups

Since Agent 1.27.0 and Dashboard 1.37.0

The dashboard only offers the Physical method for agents 1.27.0 or later. A physical backup requested from an older agent is marked as failed with Agent too old for physical backups.

A postgresql-cluster source can use the physical method instead of pg_dumpall. The agent runs pg_basebackup over the replication protocol, with server-side zstd compression:

  • the first backup is a full copy of the cluster;
  • the next ones are incrementals: they only hold the blocks changed since the previous backup, and are chained to it;
  • a new full backup starts the next chain once the current one is full_every_days old, or at the times of an optional full backup schedule that replaces full_every_days, or when you click Full backup.

Use it for large clusters, where a nightly pg_dumpall is too slow or too big. A restore produces a ready-to-start data directory (not SQL), next to the running server, which is never touched.

Server requirements

  • PostgreSQL 17 or later (incremental pg_basebackup and pg_combinebackup first shipped in 17). Use the Archive method on older servers.
  • A role with the REPLICATION attribute. Superuser is not needed.
  • A pg_hba.conf line allowing replication connections from the agent. The all database keyword does not match replication connections: add an explicit replication line.
  • summarize_wal = on.
  • No custom tablespaces.
On the PostgreSQL server
CREATE ROLE portabase_backup WITH LOGIN REPLICATION PASSWORD 'change-me';
ALTER SYSTEM SET summarize_wal = on;
SELECT pg_reload_conf();
pg_hba.conf
host  replication  portabase_backup  10.0.0.0/8  scram-sha-256

On a managed service, set the summarize_wal parameter in the provider's console. The provider must also allow replication connections.

Before each backup, the agent checks these requirements and fails with the command to run when one is missing (for example Run: ALTER ROLE ... WITH REPLICATION;).

Configuration

Add a PostgreSQL Cluster database and pick Physical (incremental) as the Method. The method is set at creation and cannot be changed afterwards. Start a new full backup every N days sets full_every_days. The option is greyed out while the agent is older than 1.27.0.

OptionTypeDefaultDescription
methodstring"archive"archive (pg_dumpall) or physical. Any other value is refused when the agent loads its configuration.
full_every_daysinteger7Age, in days, of a chain's full backup after which the next backup is a new full. A whole number of at least 1; anything else is refused. Not applied while the source has a full backup schedule.

database is only used to connect for the pre-backup checks (default postgres). keep_ownership and clean_mode do not apply: a physical backup copies the whole cluster as it is.

How a chain grows

For each backup, the dashboard offers the agent a parent: the newest successful backup whose whole chain is present on every storage of the source. The agent then takes a full backup instead of an incremental when:

  • there is no parent (first backup, or a link of the chain is missing on a storage);
  • the chain's full backup is full_every_days old or older, and the source has no full backup schedule;
  • the source's full backup schedule had an occurrence since the last full backup, or you clicked Full backup (see below);
  • the server's system identifier changed (failover to another cluster, restored server);
  • the incremental pg_basebackup fails, for example because the WAL summaries it needs were removed (wal_summary_keep_time, 10 days by default). The job log shows Incremental backup failed (...); taking a full backup instead.

Each incremental is checked with pg_verifybackup before it is uploaded. Every backup carries the WAL needed to make it consistent, so no WAL archive is required.

Each backup starts with a spread checkpoint on the server (no --checkpoint=fast), so the server's I/O is not spiked. After heavy writes, the job can wait up to checkpoint_timeout before copying starts; the job log says when it is waiting.

The backup list groups each chain under its full backup: expand a full to see the incrementals built on it, in the order they were taken, with the number of incrementals, the size of the chain and the latest point it can be restored to. Hovering an incremental's arrow shows the backup it is built on. The newest chain is expanded when the page opens. Selecting a full selects its incrementals too, and deleting it deletes them.

Long backups

The dashboard marks a backup as failed when it is still running STALE_BACKUP_THRESHOLD_HOURS (6 by default) after it was requested, and then refuses its upload: the agent's work is lost. If a full backup of your cluster can take longer, raise STALE_BACKUP_THRESHOLD_HOURS on the dashboard above the longest full backup you expect, with some margin.

Full backup schedule and Full backup button

The schedule dialog (clock icon) of a physical source has two settings that do different things:

SettingWhat it decides
When backups run (automatic backups)When backups run. Each run takes one backup.
Start a new full backup (scheduled full backups)Which backups are full ones. It never starts a backup by itself: the first backup at or after each of its times is a full backup and starts a new chain.

For example, with backups every day at 03:00 (0 3 * * *) and full backups every Sunday at 02:00 (0 2 * * 0), the Sunday 03:00 run is a full backup and the Monday to Saturday runs are incrementals on it. With automatic backups off, the first backup you start after each full time is a full one. The full schedule is evaluated in the dashboard's time zone.

The full backup schedule replaces full_every_days: while it is on, a chain only restarts at its times, when you click Full backup, or for one of the technical reasons above, however old the chain is. With it off, a new full starts when the chain is full_every_days old (7 by default). For a source defined in the agent's databases.json, the dashboard does not know full_every_days: the dialog names the setting, and its preview of the next backups cannot show the fulls it starts.

Next to Backup, Full backup starts a new chain right away. The job log of such a backup starts with Full backup: full backup requested from the dashboard (or the full backup schedule (...) is due).

Deletion and retention

An incremental is useless without the backups it depends on, so chains are kept whole:

  • deleting a backup from a storage also deletes, on that storage, every backup that depends on it; Delete entire backup does the same on every storage. Deleting the newest incremental removes only that one;
  • retention policies never delete a backup that a kept backup depends on. Full and incremental backups count the same in keep N and keep N days rules.

For example, with a full F1 on Sunday, incrementals I1 to I6 from Monday to Saturday, a full F2 the next Sunday and I7 on Monday, keep 7 keeps I7, F2 and I6 to I2. I1 and F1 are expired, but I2 needs them, so they stay. They are deleted, with the rest of the first chain, once no kept backup depends on them. A chain can therefore outlive the retention period by up to one full backup interval.

When a new full backup starts a chain, the previous chain is not changed and every backup in it can still be restored. The next backups are incrementals on the new full; the previous chain only goes away through retention or deletion. If the new full fails, the next backup continues the previous chain.

Restore

A physical restore is done by the agent: it rebuilds a data directory with pg_combinebackup, then checks it with pg_verifybackup. The running server is never touched. The directory is written under:

$RESTORE_PATH/<source generated_id>/<UTC timestamp>/data/            # PostgreSQL 17
$RESTORE_PATH/<source generated_id>/<UTC timestamp>/<major>/docker/  # PostgreSQL 18 and later

The end of the restore job log prints how to start the restored directory with any PostgreSQL install of the same major version:

PGDATA='/restores/<source generated_id>/<UTC timestamp>/18/docker'
chown -R postgres:postgres "$PGDATA" && chmod 700 "$PGDATA"
pg_ctl -D "$PGDATA" start    # as the postgres OS user

The path in the log is the agent's: on the host, the directory is under the folder mounted at RESTORE_PATH. With Docker, mount it in the official postgres:<major> image instead (/var/lib/postgresql for 18 and later, the data folder at /var/lib/postgresql/data before). If postgresql.conf, pg_hba.conf or pg_ident.conf live outside the data directory on the source (Debian-style /etc/postgresql/<major>/main), the log asks you to copy them into $PGDATA before starting.

Every backup of the chain must be present on the storage you restore from; otherwise the restore is refused and names the missing backup.

RESTORE_PATH is required

A physical restore is refused, before anything is downloaded, unless RESTORE_PATH points to an existing, writable directory. Mount a host folder there so the restored directory survives the agent container.

docker-compose.yml (agent)
services:
  agent:
    image: portabase/agent:latest
    volumes:
      - ./databases.json:/config/config.json
      - ./restores:/restores
    environment:
      RESTORE_PATH: /restores

With Helm, set volume.restore.enabled=true together with volume.restore.hostPath or volume.restore.existingClaim. volume.restore.mountPath (default /restores) is also exported as RESTORE_PATH.

Disk space

  • Backup: the agent builds each backup in TMPDIR. Plan for the compressed size of a full backup, plus the uncompressed size of an incremental (it is extracted once for pg_verifybackup).
  • Restore: the downloaded backups, their extracted copies and the rebuilt directory all live under RESTORE_PATH during the restore. Plan for about three times the size of the cluster. Downloads and extracted files are removed when the restore ends.

Example: PostgreSQL in Docker Compose

docker-compose.yml
services:
  postgres:
    image: postgres:18-alpine
    command: ["postgres", "-c", "summarize_wal=on"]
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: mysecretpassword
    volumes:
      - postgres_data:/var/lib/postgresql
      - ./physical-init.sh:/docker-entrypoint-initdb.d/10-physical.sh:ro
    networks:
      - portabase
physical-init.sh (chmod +x, runs on the first start only)
#!/bin/sh
set -eu
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<'SQL'
CREATE ROLE portabase_backup WITH LOGIN REPLICATION PASSWORD 'change-me';
SQL
echo "host replication portabase_backup all scram-sha-256" >> "$PGDATA/pg_hba.conf"

Docker Compose Example

Here is how to configure a PostgreSQL service alongside the agent.

docker-compose.yml
services:
  postgres:
    image: postgres:15-alpine
    container_name: my-postgres
    restart: always
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: mysecretpassword
      POSTGRES_DB: app_db
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - portabase

  agent:
    image: portabase/agent:latest
    # ... agent configuration ...
    depends_on:
      - postgres
    networks:
      - portabase

networks:
  portabase:
    external: true

volumes:
  postgres_data:

Note that in this example, the host (host) to enter in the agent configuration will be postgres (the service name), not localhost.

Last updated on

On this page