How to Backup and Restore a PostgreSQL Database
In a production environment, no matter how large or small your PostgreSQL database may be, regular backup is an essential aspect of database management. In this article, you will learn how to backup and restore a PostgreSQL database.
We assume that you already have a working installation of the PostgreSQL database system. If not, read our following articles to install PostgreSQL on your Linux distribution.
You might also like:
- How to Install PostgreSQL from Source in Linux
- How to Install PostgreSQL and pgAdmin4 in Ubuntu 20.04
- How to Install PostgreSQL 15 and pgAdmin in RHEL 9
- How to Install PostgreSQL and pgAdmin in CentOS 8
- How to Install PostgreSQL and pgAdmin in RHEL 8
Let’s get started…
Backup a Single PostgreSQL Database
PostgreSQL provides the pg_dump utility to help you back up databases. It generates a database file with SQL commands in a format that can be easily restored in the future.
To back up a PostgreSQL database, start by logging into your database server, then switch to the Postgres user account, and run pg_dump as follows (replace tecmintdb
with the name of the database you want to backup). By default, the output format is a plain-text SQL script file.
<code>$ pg_dump <strong>tecmintdb</strong> > <strong>tecmintdb.sql</strong></code>
The pg_dump supports other output formats as well. You can specify the output format using the -F
option, where c
means custom format archive file, d
means directory format archive, and t
means tar format archive file: all formats are suitable for input into pg_restore.
For example:
<code>$ pg_dump -F c tecmintdb > tecmintdb.dump OR $ pg_dump -F t tecmintdb > tecmintdb.tar</code>
To dump output in the directory output format, use the -f
flag (which is used to specify the output file) to specify the target directory instead of a file. The directory which will be created by pg_dump must not exist.
<code>$ pg_dump -F d tecmintdb -f tecmintdumpdir </code>
To back up all PostgreSQL databases, use the pg_dumpall tool as shown.
<code>$ pg_dumpall > all_pg_dbs.sql</code>
You can restore the dump using psql as shown.
<code>$ psql -f all_pg_dbs.sql postgres</code>
Restoring a PostgreSQL Database
To restore a PostgreSQL database, you can use the psql or pg_restore utilities. psql is used to restore text files created by pg_dump whereas pg_restore is used to restore a PostgreSQL database from an archive created by pg_dump in one of the non-plain-text formats (custom, tar, or directory).
Here is an example of how to restore a plain text file dump:
<code>$ psql <strong>tecmintdb</strong> tecmintdb.sql</code>
As mentioned above, a custom-format dump is not a script for psql, so it must be restored with pg_restore as shown.
<code>$ pg_restore -d tecmintdb tecmintdb.dump OR $ pg_restore -d tecmintdb tecmintdb.tar OR $ pg_restore -d tecmintdb tecmintdumpdir </code>
Compressed PostgreSQL Database Backup
If the database you are backing up is large and you want to generate a fairly smaller output file, then you can run a compressed dump where you have to filter the output of pg_dump via a compression tool such as gzip or any of your favorite:
<code>$ pg_dump <strong>tecmintdb</strong> | gzip > <strong>tecmintdb.gz</strong></code>
If the database is extremely large, you can dump in parallel by dumping number_of_jobs tables simultaneously using the -j
flag, as shown.
<code>$ pg_dump -F d -j 5 -f tecmintdumpdir</code>
It is important to note that the parallel dump option reduces the time of the dump, but on the other hand, it also increases the load on the database server.
Backup Remote PostgreSQL Databases
pg_dump is a regular PostgreSQL client tool, it supports operations on remote database servers. To specify the remote database server pg_dump should contact, use the command-line options -h
to specify the remote host and -p
specifies the remote port the database server is listening on. Besides, use the -U
flag to specify the database role name to connect as.
Remember to replace 10.10.20.10 and 5432 and tecmintdb with your remote host IP address or hostname, database port, and database name respectively.
<code>$ pg_dump -U tecmint -h 10.10.20.10 -p 5432 tecmintdb > tecmintdb.sql</code>
Ensure that the user connecting remotely has the required privileges to access the database, and the appropriate database authentication method is configured on the database server, otherwise, you will get an error like the one shown in the following screenshot.
It is also possible to dump a database directly from one server to another, use the pg_dump and psql utilities as shown.
<code>$ pg_dump -U tecmint -h 10.10.20.10 tecmintdb | pqsl -U tecmint -h 10.10.20.30 tecmintdb</code>
Auto Backup PostgreSQL Database Using a Cron Job
You can perform backups at regular intervals using cron jobs. Cron jobs are a commonly used means for scheduling various kinds of tasks to run on a server.
You can configure a cron job to automate PostgreSQL database backup as follows. Note that you need to run the following commands as the PostgreSQL superuser:
<code>$ mkdir -p /srv/backups/databases</code>
Next, run the following command to edit the crontab to add a new cron job.
<code>$ crontab -e</code>
Copy and paste the following line at the end of the crontab. You can use any of the dump formats explained above.
<code>0 0 * * * pg_dump -U postgres tecmintdb > /srv/backups/postgres/tecmintdb.sql</code>
Save the file and exit.
The cron service will automatically start running this new job without a restart. And this cron job will run every day at midnight, it is a minimum solution to the backup task.
For more information on how to schedule cron jobs, see: How to Create and Manage Cron Jobs on Linux
That’s it for now! It’s a good idea to make backing up data a part of your database management routine. To reach us for any questions or comments, use the feedback form below. For more information, see the pg_dump and pg_restore reference pages.
The above is the detailed content of How to Backup and Restore a PostgreSQL Database. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

LXD is described as the next-generation container and virtual machine manager that offers an immersive for Linux systems running inside containers or as virtual machines. It provides images for an inordinate number of Linux distributions with support

Clear Linux OS is the ideal operating system for people – ahem system admins – who want to have a minimal, secure, and reliable Linux distribution. It is optimized for the Intel architecture, which means that running Clear Linux OS on AMD sys

The key steps for creating a self-signed SSL certificate are as follows: 1. Generate the private key, use the command opensslgenrsa-outselfsigned.key2048 to generate a 2048-bit RSA private key file, optional parameter -aes256 to achieve password protection; 2. Create a certificate request (CSR), run opensslreq-new-keyselfsigned.key-outselfsigned.csr and fill in the relevant information, especially the "CommonName" field; 3. Generate the certificate by self-signed, and use opensslx509-req-days365-inselfsigned.csr-signk

Firefox browser is the default browser for most modern Linux distributions such as Ubuntu, Mint, and Fedora. Initially, its performance might be impressive, however, with the passage of time, you might notice that your browser is not as fast and resp

Decompress the .zip file on Windows, you can right-click to select "Extract All", while the .tar.gz file needs to use tools such as 7-Zip or WinRAR; on macOS and Linux, the .zip file can be double-clicked or unzip commanded, and the .tar.gz file can be decompressed by tar command or double-clicked directly. The specific steps are: 1. Windows processing.zip file: right-click → "Extract All"; 2. Windows processing.tar.gz file: Install third-party tools → right-click to decompress; 3. macOS/Linux processing.zip file: double-click or run unzipfilename.zip; 4. macOS/Linux processing.tar

When encountering DNS problems, first check the /etc/resolv.conf file to see if the correct nameserver is configured; secondly, you can manually add public DNS such as 8.8.8.8 for testing; then use nslookup and dig commands to verify whether DNS resolution is normal. If these tools are not installed, you can first install the dnsutils or bind-utils package; then check the systemd-resolved service status and configuration file /etc/systemd/resolved.conf, and set DNS and FallbackDNS as needed and restart the service; finally check the network interface status and firewall rules, confirm that port 53 is not

As a system administrator, you may find yourself (today or in the future) working in an environment where Windows and Linux coexist. It is no secret that some big companies prefer (or have to) run some of their production services in Windows boxes an

If you find that the server is running slowly or the memory usage is too high, you should check the cause before operating. First, you need to check the system resource usage, use top, htop, free-h, iostat, ss-antp and other commands to check CPU, memory, disk I/O and network connections; secondly, analyze specific process problems, and track the behavior of high-occupancy processes through tools such as ps, jstack, strace; then check logs and monitoring data, view OOM records, exception requests, slow queries and other clues; finally, targeted processing is carried out based on common reasons such as memory leaks, connection pool exhaustion, cache failure storms, and timing task conflicts, optimize code logic, set up a timeout retry mechanism, add current limit fuses, and regularly pressure measurement and evaluation resources.
