Este contenido no está disponible en el idioma seleccionado.
Chapter 3. Using PostgreSQL
The PostgreSQL server is an open source robust and highly-extensible database server based on the SQL language. The PostgreSQL server provides an object-relational database system that can manage extensive datasets and a high number of concurrent users.
The PostgreSQL server includes features for ensuring data integrity, building fault-tolerant environments and applications. With the PostgreSQL server, you can extend a database with your own data types, custom functions, or code from different programming languages without the need to recompile the database.
Learn how to install and configure PostgreSQL on a RHEL system, how to back up PostgreSQL data, and how to migrate from an earlier PostgreSQL version.
3.1. Installing PostgreSQL Copiar enlaceEnlace copiado en el portapapeles!
RHEL 10 provides PostgreSQL 16 as the initial version of the Application Stream, which you can install as an RPM package. In minor releases, RHEL 10 provides additional PostgreSQL versions as alternative versions with a shorter life cycle.
In RHEL 10, the PostgreSQL server is available in the following versions:
- PostgreSQL 16
- PostgreSQL 18 available since RHEL 10.2
By design, you can install only one version (stream) of the same application stream and, because of conflicting RPM packages, you cannot install multiple PostgreSQL instances on the same host. As an alternative, you can run the database server services in a container. See Using containers to run multiple PostgreSQL instances on a single host.
Procedure
Install the PostgreSQL server packages:
For PostgreSQL 16, enter:
# dnf install postgresql-serverFor PostgreSQL 18, enter:
# dnf install postgresql18-server
The
postgressuperuser is created automatically.Initialize the database cluster:
# postgresql-setup --initdbStore the data in the default
/var/lib/pgsql/datadirectory.Enable and start the
postgresqlservice:# systemctl enable --now postgresql.service
3.2. Using containers to run multiple PostgreSQL instances on a single host Copiar enlaceEnlace copiado en el portapapeles!
If you install PostgreSQL from packages, you can run only a single version of it on the same host. To run multiple instances or different versions of PostgreSQL, you can run the service in a container.
Prerequisites
-
The
podmanpackage is installed.
Procedure
Authenticate to the
registry.redhat.ioregistry by using your Red Hat Customer Portal account:# podman login registry.redhat.ioSkip this step if you are already logged in to the container registry.
Start the containers you want to use.
For PostgreSQL 16, enter:
$ podman run -d --name <container_name> -e POSTGRESQL_USER=<user_name> -e POSTGRESQL_PASSWORD=<password> -p <host_port_1>:5432 rhel10/postgresql-16For more information about the usage of this container image, see the Red Hat Ecosystem Catalog.
For PostgreSQL 18, enter:
$ podman run -d --name <container_name> -e POSTGRESQL_USER=<user_name> -e POSTGRESQL_PASSWORD=<password> -p <host_port_2>:5432 rhel10/postgresql-18For more information about the usage of this container image, see the Red Hat Ecosystem Catalog.
ImportantThe container names and host ports of the two database servers must differ.
To ensure that clients can access the database server on the network, open the host ports in the firewall:
# firewall-cmd --permanent --add-port={<host_port_1>/tcp,<host_port_2>/tcp,...} # firewall-cmd --reload
Verification
Connect to the database server and log in as root:
# psql -u postgres -p -h localhost -P <host_port> --protocol tcpDisplay information about running containers:
$ podman ps
3.3. Creating PostgreSQL users Copiar enlaceEnlace copiado en el portapapeles!
You can create PostgreSQL users with specific permissions to manage database access and control user privileges for secure database administration.
PostgreSQL users are of the following types:
-
The
postgresLinux system user: Use it only to run the PostgreSQL server and client applications, such aspg_dump. Do not use thepostgressystem user for any interactive work on PostgreSQL administration, such as database creation and user management. -
A database superuser: The default
postgresPostgreSQL superuser is not related to thepostgressystem user. You can limit access of thepostgressuperuser in the/var/lib/pgsql/data/pg_hba.conffile, otherwise no other permission limitations exist. You can also create other database superusers. A role with specific database access permissions:
- A database user: Has a permission to log in by default.
- A group of users: Enables managing permissions for the group as a whole.
Roles can own database objects (for example, tables and functions) and can assign object privileges to other roles by using SQL commands.
Standard database management privileges include SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER, CREATE, CONNECT, TEMPORARY, EXECUTE, and USAGE.
Role attributes are special privileges, such as LOGIN, SUPERUSER, CREATEDB, and CREATEROLE.
Perform most tasks as a role that is not a superuser. A common practice is to create a role that has the CREATEDB and CREATEROLE privileges and use this role for all routine management of databases and roles.
Prerequisites
- The PostgreSQL server is installed.
- The database cluster is initialized.
-
The
password_encryptionparameter in the/var/lib/pgsql/data/postgresql.conffile is set toscram-sha-256. -
Entries in the
/var/lib/pgsql/data/pg_hba.conffile use thescram-sha-256hashing algorithm as authentication method.
Procedure
Log in as the
postgressystem user, or switch to this user:# su - postgresStart the PostgreSQL interactive shell prompt:
$ psql psql (16.4) Type "help" for help. postgres=#Optional: Obtain information about the current database connection:
postgres=# \conninfo You are connected to database "postgres" as user "postgres" via socket in "/var/run/postgresql" at port "5432".Create a user named
mydbuser, set a password for it, and assign theCREATEROLEandCREATEDBpermissions to the user:postgres=# CREATE USER mydbuser WITH PASSWORD '<password>' CREATEROLE CREATEDB; CREATE ROLEThe
mydbuseruser now can perform routine database management operations: create databases and manage user indexes.Log out of the interactive shell prompt by using the
\qmeta command:postgres=# \q
Verification
Log in to PostgreSQL as
mydbuser, specify the hostname, and connect to the defaultpostgresdatabase, which was created during initialization:# psql -U mydbuser -h 127.0.0.1 -d postgres Password for user mydbuser: Type the password. psql (16.4) Type "help" for help. postgres=>Create a database:
postgres=> CREATE DATABASE <db_name>;Log out of the session:
postgres=# \qConnect to new database as
mydbuser:# psql -U mydbuser -h 127.0.0.1 -d <db_name> Password for user mydbuser: psql (16.4) Type "help" for help. mydatabase=>
3.4. Configuring PostgreSQL Copiar enlaceEnlace copiado en el portapapeles!
You can configure PostgreSQL by editing the configuration files in the database cluster directory to set database parameters, authentication, and client access. By default, PostgreSQL uses the /var/lib/pgsql/data/ directory.
The PostgreSQL configuration files include:
-
/var/lib/pgsql/data/postgresql.conf- sets the database cluster parameters. -
/var/lib/pgsql/data/postgresql.auto.conf- holds basic PostgreSQL settings similarly topostgresql.conf. However, this file is under the server’s control. TheALTER SYSTEMqueries edit this file. You cannot edit it manually. -
/var/lib/pgsql/data/pg_ident.conf- maps user identities from external authentication mechanisms into the PostgreSQL user identities. -
/var/lib/pgsql/data/pg_hba.conf- configures client authentication for PostgreSQL databases.
Procedure
Edit the
/var/lib/pgsql/data/postgresql.conffile and configure basic settings of the database cluster parameters, for example:log_connections = yes log_destination = 'syslog' search_path = '"$user", public' shared_buffers = 128MB password_encryption = scram-sha-256Edit the
/var/lib/pgsql/data/pg_hba.conffile and configure client authentication, for example:# TYPE DATABASE USER ADDRESS METHOD local all all trust host postgres all 192.168.93.0/24 ident host all all .example.com scram-sha-256Restart the
postgresqlservice so that the changes become effective:# systemctl restart postgresql.service
3.5. Configuring TLS encryption on a PostgreSQL server Copiar enlaceEnlace copiado en el portapapeles!
By default, PostgreSQL uses unencrypted connections. For more secure connections, you can enable Transport Layer Security (TLS) support on the PostgreSQL server and configure your clients to establish encrypted connections.
Prerequisites
- You created a TLS private key and a certificate authority (CA) issued a server certificate for your PostgreSQL server.
- The PostgreSQL server is installed.
- The database cluster is initialized.
- If FIPS mode is enabled, clients must either support the Extended Master Secret (EMS) extension or use TLS 1.3. TLS 1.2 connections without EMS fail. For more information, see the Red Hat Knowledgebase solution TLS extension "Extended Master Secret" enforced on RHEL 9.2 and later.
Procedure
Store the private key and the server certificate in the
/var/lib/pgsql/data/directory:# cp server.{key,crt} /var/lib/pgsql/data/Set the ownership of the private key and certificate:
# chown postgres:postgres /var/lib/pgsql/data/server.{key,crt}Set permissions on the server certificate that enable only the PostgreSQL server to read the file:
# chmod 0400 /var/lib/pgsql/data/server.keyBecause certificates are part of the communication before the server establishes a secure connection, any client can retrieve them without authentication. Therefore, you do not need to set strict permissions on the server certificate file.
Edit the
/var/lib/pgsql/data/postgresql.conffile and make the following changes:Set the
scram-sha-256hashing algorithm:password_encryption = scram-sha-256Enable TLS encryption:
ssl = onConfigure TLS ciphers to follow the system crypto profile:
By default, PostgreSQL sets
ssl_cipherstoHIGH:MEDIUM:+3DES:!aNULL, which is a fixed OpenSSL cipher list that might not match your system-wide cryptographic policy. Replace this value withPROFILE=SYSTEMso that PostgreSQL does not offer TLS cipher suites that the system profile disallows:ssl_ciphers = 'PROFILE=SYSTEM'
Edit the
/var/lib/pgsql/data/pg_hba.conffile and update the authentication entries to use TLS encryption and thescram-sha-256hashing algorithm. For example, changehostentries tohostsslto enable TLS encryption, and set thescram-sha-256hashing algorithm in the last column:hostssl all all 192.0.2.0/24 scram-sha-256Restart the
postgresqlservice:# systemctl restart postgresql.service
Verification
Use the
postgressuper user to connect to a PostgreSQL server and run the\conninfometa command:# psql "postgresql://postgres@localhost:5432" -c '\conninfo' Password for user postgres: You are connected to database "postgres" as user "postgres" on host "192.0.2.1" at port "5432". SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)
3.6. Backing up and restoring PostgreSQL data with logical dumps Copiar enlaceEnlace copiado en el portapapeles!
A logical backup of PostgreSQL data consists of the SQL statements necessary to restore the data. The advantage of logical backup over physical backup is that you can restore data from logical backup on other hardware configurations and PostgreSQL versions.
The SQL dump method generates a dump file containing SQL commands. Uploading the file to the database server recreates the database in its state at the time of the dump.
The following PostgreSQL client applications ensure SQL dumps:
-
pg_dumpdumps a single database without cluster-wide information about roles or tablespaces -
pg_dumpalldumps each database in a given cluster and preserves cluster-wide data, such as role and tablespace definitions.
By default, the pg_dump and pg_dumpall commands write their results into the standard output. To store the dump in a file, redirect the output to an SQL file. The resulting SQL file can be either in a text format or in other formats that allow for parallelism and for more detailed control of object restoration.
You can perform the SQL dump from any remote host that has access to the database.
3.6.1. Advantages and disadvantages of an SQL dump Copiar enlaceEnlace copiado en el portapapeles!
SQL dumps are text files containing a database’s structure and data in the form of SQL statements.
Advantages:
-
An SQL dump is the only PostgreSQL backup method that is not server version-specific. You can reload the output of the
pg_dumputility into later versions of PostgreSQL, which is not possible for file system level backups or continuous archiving. - An SQL dump is the only method that works when transferring a database to a different machine architecture, such as going from a 32-bit to a 64-bit server.
-
An SQL dump provides internally consistent dumps. A dump represents a snapshot of the database at the time
pg_dumpbegan running. -
The
pg_dumputility does not block other operations on the database when it is running.
Disadvantage:
- An SQL dump takes more time compared to a file system level backup.
3.6.2. Backing up a single PostgreSQL database by using pg_dump Copiar enlaceEnlace copiado en el portapapeles!
You can create a backup of a single PostgreSQL database by using the pg_dump utility to export the database structure and data to a file.
Prerequisites
-
You are logged in as the
postgressuperuser or a user with database administrator privileges.
Procedure
Dump a database without cluster-wide information:
$ pg_dump <db_name> > <dump_file>To specify which database server
pg_dumpcontacts, use the following command-line options:The
-hoption to define the host.The default host is either the local host or what the
PGHOSTenvironment variable specifies.The
-poption to define the port.The
PGPORTenvironment variable indicates the default port or the compiled-in default.
3.6.3. Restoring a single PostgreSQL database by using pg_dump Copiar enlaceEnlace copiado en el portapapeles!
You can restore a PostgreSQL database from an SQL dump file by using the pg_restore utility to re-create the database structure and data.
Prerequisites
-
You are logged in as the
postgressuperuser or a user with database administrator privileges.
Procedure
Create a new database:
$ createdb <db_name>- Verify that all users who own objects or have permissions on objects in the dumped database already exist. If such users do not exist, the restore fails to re-create the objects with the original ownership and permissions.
Run the
psqlutility to restore a text file dump created by thepg_dumputility:$ psql <db_name> < <dump_file>where
<dump_file>is the output of thepg_dumpcommand. To restore a non-text file dump, use thepg_restoreutility instead:$ pg_restore <non-plain_text_file>
3.6.4. Backing up all databases on a PostgreSQL server by using pg_dumpall Copiar enlaceEnlace copiado en el portapapeles!
You can create a backup of all databases on a PostgreSQL server by using the pg_dumpall utility to export all databases and cluster-wide data to a single file.
Prerequisites
-
You are logged in as the
postgressuperuser or a user with database administrator privileges.
Procedure
Dump all databases in the database cluster and preserve cluster-wide data:
$ pg_dumpall > <dump_file>To specify which database server
pg_dumpallcontacts, use the following command-line options:The
-hoption to define the host.The default host is either the local host or what the
PGHOSTenvironment variable specifies.The
-poption to define the port.The
PGPORTenvironment variable indicates the default port or the compiled-in default.The
-loption to define the default database.This option enables you to choose a default database different from the
postgresdatabase created automatically during initialization.
3.6.5. Restoring all databases on a PostgreSQL server by using pg_dumpall Copiar enlaceEnlace copiado en el portapapeles!
You can restore all databases on a PostgreSQL server from a pg_dumpall file by using the psql utility to re-create the entire database cluster.
Prerequisites
-
You are logged in as the
postgressuperuser or a user with database administrator privileges.
Procedure
- Ensure that all users who own objects or were granted permissions on objects in the dumped databases already exist. If such users do not exist, the restore fails to re-create the objects with the original ownership and permissions.
Run the
psqlutility to restore a text file dump created by thepg_dumpallutility:$ psql < <dump_file>where
<dump_file>is the output of thepg_dumpallcommand.
3.6.6. Handling SQL errors during restore Copiar enlaceEnlace copiado en el portapapeles!
By default, the psql utility continues to run if an SQL error occurs, causing the database to restore only partially. Alternatively, you can configure psql to stop on errors to ensure data integrity.
Prerequisites
-
You are logged in as the
postgressuperuser or a user with database administrator privileges.
Procedure
Make
psqlexit with an exit status of 3 if an SQL error occurs by setting theON_ERROR_STOPvariable:$ psql --set ON_ERROR_STOP=on <db_name> < <dump_file>Specify that the whole dump is restored as a single transaction so that the restore is either fully completed or canceled.
When restoring a text file dump by using the
psqlutility:$ psql -1When restoring a non-text file dump by using the
pg_restoreutility:$ pg_restore -e
Note that when you use this approach, even a minor error can cancel a restore operation that has already run for many hours.
3.7. Backing up and restoring PostgreSQL data with physical copies Copiar enlaceEnlace copiado en el portapapeles!
A physical backup of PostgreSQL data contains files and directories that store the content. This method is typically faster and smaller in size.
3.7.1. Performing a file system backup on a PostgreSQL server Copiar enlaceEnlace copiado en el portapapeles!
A file system-level backup is a fast way to back up a complete PostgreSQL instance. This method requires a shutdown of the postgresql service for data consistency.
A PostgreSQL file system-level backup is specific to an architecture and RHEL major version. You cannot restore data that you backed up by this method on a different architecture or RHEL major version.
Procedure
Stop the
postgresqlservice:# systemctl stop postgresql.serviceCreate a backup directory, for example:
# mkdir -p /root/postgresql-backup/Back up the
/var/lib/pgsql/directory:# cp -rp /var/lib/pgsql/ /root/postgresql-backup/The
/var/lib/pgsql/contains all essential files of the PostgreSQL database server, including configuration files, data files, and logs.Start the
postgresqlservice:# systemctl start postgresql.service
3.7.2. Restoring a file system backup on a PostgreSQL server Copiar enlaceEnlace copiado en el portapapeles!
If your PostgreSQL instance is corrupt and you previously performed a file system backup that includes the data directory, you can restore the instance from this backup.
Prerequisites
- You performed a file system backup on a PostgreSQL server.
The target server must meet the following conditions of the backup source:
- The PostgreSQL version must be identical.
- The system architecture must be identical.
Procedure
Stop the
postgresqlservice:# systemctl stop postgresql.serviceRemove the current
/var/lib/pgsql/directory:# rm -rf /var/lib/pgsql/Restore the data directory from your backup:
# cp -rp /root/postgresql-backup/pgsql/ /var/lib/Ensure the correct ownership of the
/var/lib/pgsql/directory:# chown -R postgres:postgres /var/lib/pgsql/Restore the SELinux context of the
/var/lib/pgsql/directory:# restorecon -Rv /var/lib/pgsql/Start the
postgresqlservice:# systemctl start postgresql.service
Verification
-
Log in as the
postgresuser. Connect to a database:
$ psql <database>Access data in the database:
<database>=# SELECT * FROM <table>;Disconnect from the PostgreSQL service:
<database>=# \q
3.8. Backing up and restoring PostgreSQL data with continuous archiving Copiar enlaceEnlace copiado en el portapapeles!
You can use continuous archiving to create robust PostgreSQL backups by combining WAL files with base backups for point-in-time recovery and high availability.
PostgreSQL records every change to the database’s data files to a write-ahead log (WAL) file that is available in the pg_wal/ subdirectory of the cluster’s data directory. This log primarily serves crash recovery. After a crash, you can use log entries made since the last checkpoint to restore the database to a consistent state.
The continuous archiving method, or online backup, combines WAL files with a database cluster copy from a running-server base backup or file system-level backup.
To recover the system to its current state, restore the database cluster copy and replay the backed-up WAL files.
With the continuous archiving method, you must keep a continuous sequence of all archived WAL files that extends at minimum back to the start time of your last base backup. Therefore the ideal frequency of base backups depends on:
- The storage volume available for archived WAL files.
- The maximum possible duration of data recovery in situations when recovery is necessary. In cases with a long period since the last backup, the system replays more WAL segments, and the recovery therefore takes more time.
You cannot use pg_dump and pg_dumpall SQL dumps as a part of a continuous archiving backup solution. SQL dumps produce logical backups and do not contain enough information for WAL replay.
3.8.1. Advantages and disadvantages of continuous archiving Copiar enlaceEnlace copiado en el portapapeles!
Continuous archiving is a feature that provides a robust strategy for data backup, high availability, and point-in-time recovery (PITR) by continuously saving the database’s transaction log files.
Advantages:
- With the continuous backup method, you can use a base backup that is not entirely consistent because the log replay corrects any internal inconsistency. Therefore you can perform a base backup on a running PostgreSQL server.
-
You do not need a file system snapshot;
taror a similar archiving utility is sufficient. - You can achieve continuous backup by continuing to archive the WAL files because the sequence of WAL files for the log replay can be indefinitely long. This is particularly valuable for large databases.
- Continuous backup supports point-in-time recovery. It is not necessary to replay the WAL entries to the end. You can stop the replay at any point and restore the database to its state at any time since the base backup was taken.
- If WAL files remain continuously available on another machine that has the same base backup, you can restore the database on that machine. The restored copy can be nearly current at any point.
Disadvantages:
- Continuous backup method supports only restoration of an entire database cluster, not a subset.
- Continuous backup requires extensive archival storage.
3.8.2. Setting up WAL archiving Copiar enlaceEnlace copiado en el portapapeles!
You can enable write ahead log (WAL) archiving on your PostgreSQL server to capture and save WAL segment files for backup and point-in-time recovery purposes.
A PostgreSQL server generates a sequence of WAL records while it runs. The server physically divides this sequence into WAL segment files and assigns each file a numeric name that reflects its position in the WAL sequence. Without WAL archiving, the server reuses the segment files and renames them with higher segment numbers.
When archiving WAL data, the server captures and saves the contents of each segment file to a new location before reusing the file. You have multiple options where to save the content, such as an NFS-mounted directory on another machine, a tape drive, or a CD.
Note that WAL records do not include changes to configuration files.
Procedure
In the
/var/lib/pgsql/data/postgresql.conffile:-
Set the
wal_levelconfiguration parameter toreplicaor higher. -
Set the
archive_modeparameter toon. Specify the shell command in the
archive_commandconfiguration parameter. You can use thecpcommand, another command, or a shell script.For example:
archive_command = 'test ! -f /mnt/server/archivedir/%f && cp %p /mnt/server/archivedir/%f'where the
%pparameter specifies the relative path to the file to archive, and the%fparameter specifies the file name.
This command copies archivable WAL segments to the
/mnt/server/archivedir/directory. After replacing the%pand%fparameters, the resulting command looks as follows:+
test ! -f /mnt/server/archivedir/00000001000000A900000065 && cp pg_wal/00000001000000A900000065 /mnt/server/archivedir/00000001000000A900000065+ A similar command is generated for each new file that is archived.
+
NoteThe archive command runs only after a WAL segment is completed. A server that generates little WAL traffic can have a substantial delay between the completion of a transaction and its safe recording in archive storage. To limit how old unarchived data can be, you can:
-
Set the
archive_timeoutparameter to force the server to switch to a new WAL segment file with a given frequency. -
Use the
pg_switch_walparameter to force a segment switch to ensure that a transaction is archived immediately after it finishes.
-
Set the
Restart the
postgresqlservice to enable the changes:# systemctl restart postgresql.service- Test your archive command and ensure it does not overwrite an existing file and that it returns a nonzero exit status if it fails.
- To protect your data, ensure that the segment files are archived into a directory that does not have group or world read access.
3.8.3. Making a base backup Copiar enlaceEnlace copiado en el portapapeles!
You can create a PostgreSQL base backup by using the pg_basebackup utility to capture a consistent snapshot of your database for backup and recovery purposes.
The base backup creates a history file in the WAL archive area, named after the first WAL segment required for the backup.
The backup history file is a small text file containing the starting and ending times, and WAL segments of the backup. If you used the label string to identify the associated dump file, you can use the backup history file to determine which dump file to restore.
Consider keeping several backup sets to be certain that you can recover your data.
Prerequisites
-
You are logged in as the
postgressuperuser, a user with database administrator privileges, or another user with at leastREPLICATIONpermissions. - You must keep all the WAL segment files generated during and after the base backup.
Procedure
Use the
pg_basebackuputility to perform the base backup.To create a base backup as individual files (plain format):
$ pg_basebackup -D <backup_directory> -FpReplace backup_directory with your chosen backup location.
If you use tablespaces and perform the base backup on the same host as the server, you must use the
--tablespace-mappingoption. Otherwise the backup fails upon an attempt to write the backup to the same location.To create a base backup as a
tararchive (tarand compressed format):$ pg_basebackup -D <backup_directory> -Ft -zReplace backup_directory with your chosen backup location.
To restore such data, you must manually extract the files in the correct locations.
To specify which database server pg_basebackup will contact, use the following command-line options:
The
-hoption to define the host.The default host is either the local host or a host specified by the
PGHOSTenvironment variable.The
-poption to define the port.The default port is indicated by the
PGPORTenvironment variable or the compiled-in default.
- After the base backup process completes, safely archive the database cluster copy and WAL segment files used during the backup, as specified in the backup history file.
- Delete WAL segments numerically lower than the WAL segment files used in the base backup because these are older than the base backup and no longer needed for a restore.
3.8.4. Restoring the database by using a continuous archive backup Copiar enlaceEnlace copiado en el portapapeles!
You can restore a PostgreSQL database by restoring the base backup and applying archived WAL files for point-in-time recovery.
Procedure
Stop the server:
# systemctl stop postgresql.serviceCopy the necessary data to a temporary location.
Preferably, copy the whole cluster data directory and any tablespaces. Note that this requires enough free space on your system to hold two copies of your existing database.
If you do not have enough space, save the contents of the cluster’s
pg_waldirectory, which can contain logs that were not archived before the system went down.- Remove all existing files and subdirectories under the cluster data directory and under the root directories of any tablespaces you are using.
Restore the database files from your base backup.
Ensure that:
-
The files are restored with the correct ownership (the database system user, not
root). - The files are restored with the correct permissions.
-
The symbolic links in the
pg_tblspc/subdirectory are restored correctly.
-
The files are restored with the correct ownership (the database system user, not
Remove any files present in the
pg_wal/subdirectory.These files resulted from the base backup and are therefore obsolete. If you did not archive
pg_wal/, re-create it with proper permissions.-
Copy any unarchived WAL segment files that you saved in step 2 into
pg_wal/. Create the
recovery.confrecovery command file in the cluster data directory and specify the shell command in therestore_commandconfiguration parameter. You can use thecpcommand, another command, or a shell script. For example:restore_command = 'cp /mnt/server/archivedir/%f "%p"'Start the server:
# systemctl start postgresql.serviceThe server enters the recovery mode and proceeds to read through the archived WAL files that it needs.
If an external error terminates the recovery process, you can restart the server to continue the recovery. When the recovery process completes, the server renames
recovery.conftorecovery.done. This prevents the server from accidentally re-entering the recovery mode after it starts normal database operations.Check the contents of the database to verify that the database has recovered into the required state.
If the database has not recovered into the required state, return to step 1. If the database has recovered into the required state, allow the users to connect by restoring the client authentication configuration in the
pg_hba.conffile.
3.9. Directly transferring a PostgreSQL database from one server to another Copiar enlaceEnlace copiado en el portapapeles!
You can use the pg_dump and psql utilities to back up a PostgreSQL database and directly restore it on another PostgreSQL server. With this method you can transfer a database in a single step without intermediate files.
Prerequisites
-
You are logged in as the
postgresuser.
Procedure
Transfer a database from the source server to a destination server:
$ pg_dump -h <source_server> <db_name> | psql -h <destination_server> <db_name>
3.10. Migrating a PostgreSQL instance from a previous RHEL version to PostgreSQL on RHEL 10 Copiar enlaceEnlace copiado en el portapapeles!
If you already run PostgreSQL on RHEL 9 and want to move the database software to a host that runs RHEL 10, you can migrate the databases.
The following migration methods are available:
- Backup and restore upgrade - This method might require more time but works in most scenarios.
-
Fast upgrade by using the
pg_upgradeutility - This method is faster but works only if you migrate from PostgreSQL 13 to 16 and the hardware architecture stays the same.
Always back up the /var/lib/pgsql/data/ directory on the source host before a PostgreSQL migration.
3.10.1. Migrating to PostgreSQL on RHEL 10 by using the backup and restore method Copiar enlaceEnlace copiado en el portapapeles!
Use the backup and restore method to migrate data from any RHEL 8 or RHEL 9 version of PostgreSQL to any equal or later version of PostgreSQL on RHEL 10.
Prerequisites
- The existing database server runs on RHEL 8 or RHEL 9 and uses a PostgreSQL version installed from the RHEL repositories.
-
The locale settings on both hosts are the same. To verify this, compare the output of the
echo $LANGcommand on both hosts.
Procedure
On the host with the existing PostgreSQL instance that you want to migrate:
Export all databases to the
/var/lib/pgsql/pgdump_file.sqlfile:# su - postgres -c "pg_dumpall > /var/lib/pgsql/pgdump_file.sql"Check the exported file:
# su - postgres -c 'less "/var/lib/pgsql/pgdump_file.sql"'Copy the database dump that you created in an earlier step and the PostgreSQL configuration files to the RHEL 10 host, for example:
# scp /var/lib/pgsql/pgdump_file.sql \ /var/lib/pgsql/data/pg_hba.conf \ /var/lib/pgsql/data/pg_ident.conf \ /var/lib/pgsql/data/postgresql.conf \ <user>@<rhel_10_host>:/tmp/
On the RHEL 10 host:
Install the
postgresql-serverpackage:# dnf install postgresql-serverInitialize the
/var/lib/pgsql/data/directory:# postgresql-setup --initdbMove the copied configuration files to the
/var/lib/pgsql/data/directory:# mv /tmp/pg_hba.conf \ /tmp/pg_ident.conf \ /tmp/postgresql.conf \ /var/lib/pgsql/data/Ensure a correct ownership of the content in the
/var/lib/pgsql/data/ directory:# chown -R postgres:postgres /var/lib/pgsql/data/Restore the SELinux context on
/var/lib/pgsql/data/:# restorecon -Rv /var/lib/pgsql/data/Enable and start the
postgresqlservice:# systemctl enable --now postgresql.serviceImport the data as the
postgresuser:# su - postgres -c 'psql -f /tmp/pgdump_file.sql postgres'- Verify your databases and ensure that your applications that use the PostgreSQL server work as expected.
3.10.2. Migrating PostgreSQL 13 from a previous RHEL version to PostgreSQL 16 on RHEL 10 by using pg_update Copiar enlaceEnlace copiado en el portapapeles!
If you want to migrate a PostgreSQL 13 instance from a previous RHEL version to PostgreSQL 16 on RHEL 10, you can use the fast upgrade method. With this method, you copy the content of the /var/lib/pgsql/data/ directory to the RHEL 10 host and the pg_update utility converts the databases.
The fast upgrade method works only if your existing PostgreSQL instance is version 13 and the hardware architecture is the same on the source and destination host. In other cases, use the backup and restore method.
Prerequisites
- The existing database server uses PostgreSQL 13.
- The hardware architecture of the current and future server is the same.
The RHEL 10 host has enough free space on the disk that holds the
/var/lib/pgsql/directory.For example, migrating a 10 GiB PostgreSQL directory requires at least 20 GiB of free disk space on the RHEL 10 host.
-
The locale settings on both hosts are the same. To verify this, compare the output of the
echo $LANGcommand on both hosts.
Procedure
On the host with the existing PostgreSQL instance that you want to migrate:
Stop the
postgresqlservice:# systemctl stop postgresql.serviceChange into the
/var/lib/pgsql/directory, and back up thedatasubdirectory:# cd /var/lib/pgsql/ # tar -zcf ~/pgdata.bak.tar.gz data/Copy the
~/pgdata.bak.tar.gzarchive to the RHEL 10 host, for example:# scp ~/pgdata.bak.tar.gz <user>@<rhel_10_host>:/tmp/
On the RHEL 10 host:
Install the required packages:
# dnf install postgresql-server postgresql-upgradeThe
postgresql-upgradepackage provides a PostgreSQL 13 server which is required during the migration.-
If you use third party PostgreSQL server modules, build them against both the
postgresql-develandpostgresql-upgrade-develpackages, and install them. Ensure that the
postgresqlservice is stopped:# systemctl stop postgresql.serviceChange into the
/var/lib/pgsql/directory, and extract the backed up data directory from the previous host:# cd /var/lib/pgsql/ # tar -zxf /tmp/pgdata.bak.tar.gzOptional: Remove the
/tmp/pgdata.bak.tar.gzarchive:# rm /tmp/pgdata.bak.tar.gzPerform the upgrade process:
# postgresql-setup --upgradeThe
postgresql-setupshell script renames the/var/lib/pgsql/data/directory to/var/lib/pgsql/data-old/and uses thepg_upgradeutility to migrate the databases to a re-created/var/lib/pgsql/data/directory.ImportantThe
pg_upgradeutility migrates only the databases and not the configuration files. After the migration,/var/lib/pgsql/data/contains only the default.conffiles. If you, previously, had custom configuration files, copy them from the/var/lib/pgsql/data-old/directory and ensure that they are compatible with the new PostgreSQL version.Enable and start the
postgresqlservice:# systemctl enable --now postgresql.serviceClean up and analyze all databases:
# su postgres -c 'vacuumdb --all --analyze-in-stages'- Verify your databases and ensure that your applications that use the PostgreSQL server work as expected.
Optional: Remove the
/var/lib/pgsql/data-old/directory which contains the databases and configuration file from before the migration.# rm -r /var/lib/pgsql/data-old/Optional: Remove the
postgresql-upgradepackage:# dnf remove postgresql-upgrade
3.11. Upgrading from a RHEL 10 version of PostgreSQL 16 to PostgreSQL 18 Copiar enlaceEnlace copiado en el portapapeles!
You can upgrade your PostgreSQL database server from version 16 to 18 on RHEL 10 to access new features and improvements.
For notable enhancements and changes, see the release note in the RHEL 10.2 Release Notes document.
Prerequisites
- The existing database server uses PostgreSQL 16 on RHEL 10.
The host has enough free space on the disk that holds the
/var/lib/pgsql/directory.For example, if the size of the directory is 10 GiB, you need at least 10 GiB extra free disk space.
Procedure
Display the current data page checksum status:
# pg_controldata /var/lib/pgsql/data | grep "Data page checksum"Data page checksum version: 0If the command returns
0, data page checksums are disabled.Stop the
postgresqlservice:# systemctl stop postgresqlIf data page checksums are disabled, determine the strategy:
If you want to enable data page checksums before the upgrade to improve data integrity:
Enable data page checksums::
# pg_checksums --enable -D /var/lib/pgsql/data/Depending on the size of your databases, this operation can take a significant amount of time.
Verify the activation:
# pg_controldata /var/lib/pgsql/data | grep "Data page checksum"Data page checksum version: 1
If you want to keep the data page checksums disabled, set the
PGSETUP_INITDB_OPTIONSenvironment option to--no-data-checksums:# export PGSETUP_INITDB_OPTIONS="--no-data-checksums"
Switch to PostgreSQL 18:
# dnf install --allowerasing postgresql18-serverImportantReview the proposed
dnftransaction carefully before proceeding. Ensure that each package from the previous version is being replaced by its equivalent in the new version. The--allowerasingoption can lead to unintended package removal if the installation list is incomplete, potentially removing more software than it installs.Install the
postgresql18-upgradepackage:# dnf install postgresql18-upgradePerform the upgrade process:
# postgresql-setup --upgradeThe
postgresql-setupshell script renames the/var/lib/pgsql/data/directory to/var/lib/pgsql/data-old/and uses thepg_upgradeutility to migrate the databases to a re-created/var/lib/pgsql/data/directory.ImportantThe
pg_upgradeutility migrates only the databases and not the configuration files. After the migration,/var/lib/pgsql/data/contains only the default.conffiles. If you, previously, had custom configuration files, copy them from the/var/lib/pgsql/data-old/directory and ensure that they are compatible with the new PostgreSQL version.Start the
postgresqlservice:# systemctl start postgresqlClean up and analyze all databases:
# su postgres -c 'vacuumdb --all --analyze-in-stages'- Verify your databases and ensure that your applications that use the PostgreSQL server work as expected.
Optional: Remove the
/var/lib/pgsql/data-old/directory, which contains the databases and configuration files from before the migration.# rm -r /var/lib/pgsql/data-old/Optional: Remove the
postgresql18-upgradepackage:# dnf remove postgresql18-upgrade