How to Backup and Restore Postgres Database

Pinterest LinkedIn Tumblr

PostgreSQL comes with built-in utilities for creating and restoring backups

Note: All commands can take the login url in the format postgres://db_user:[email protected]_host:db_port/db_name?sslmode=disable


pg_dump -U citizix -h -d dbname > dbname.sql

# With options:
# -W: prompt for password
# -F: Format
#   p - plain sql
#   c – custom-format archive
#   d – directory-format archive
#   t – tar-format archive
pg_dump -U db_user -W -F t db_name > /path/to/dump_name.tar

# Take a compressed backup of PostgreSQL database
pg_dump -U db_user -d db_name | gzip > path/to/backup.sql.gz


psql -U citizix -h -d dbname -f dbname.sql

# The -C flag is for creating a database before restoring data into it.
pg_restore -d db_name /path/to/dump_name.tar -c -U db_user

# Restoring from a compressed backup
gunzip -c path/to/backup.sql.gz | psql -U db_user -d db_name

Backing up a specific table

pg_dump -U db_user -d db_name -t table_name > path/to/backup.sql

Restoring a table from SQL file

psql -U db_user -d db_name < path/to/backup.sql

Backing up all the databases at once

pg_dumpall -U db_user > path/to/backup.sql

Restoring all the databases from the backup file

psql -U db_user < path/to/backup.sql

I am a Devops Engineer, but I would describe myself as a Tech Enthusiast who is a fan of Open Source, Linux, Automations, Cloud and Virtualization. I love learning and exploring new things so I blog in my free time about Devops related stuff, Linux, Automations and Open Source software. I can also code in Python and Golang.

Write A Comment