PostgreSQLの構成
PostgreSQLに慣れているユーザーは、インスタンスを構成するための次の3つのファイルの存在に気づいています。
postgresql.confPostgreSQLのメインランタイム構成ファイルpg_hba.confクライアント認証ファイルpg_ident.conf外部ユーザーを内部ユーザーにマッピング
PostgreSQLコンテナの宣言的構成と不変性の概念により、ユーザーはこれらのファイルに直接触れることはできません。
parameters 、pg_hba 、およびpg_ident
キーを介してカスタムpostgresql.conf 、pg_hba.conf
、およびpg_ident.conf 設定を定義することにより、Cluster
リソース定義のpostgresql セクションから構成が可能です。
これらの設定は、すべてのインスタンスで同じです。
警告
ALTER SYSTEM クエリを使用して、命令的方法でPostgreSQLインスタンスの構成を変更しないでください。通常、オペレーターによって制御されるオプションの一部を変更すると、実際にクラスターの予測不能/回復不能な状態が発生する可能性があります。さらに、 ALTER SYSTEM の変更はクラスター全体でレプリケートされません。詳細については、以下の Enabling ALTER SYSTEM を参照してください。
カスタム設定の使用に関するリファレンスはサンプルに含まれています。以下を参照してください。
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: cluster-example-custom
spec:
instances: 3
# Parameters and pg_hba configuration will be append
# to the default ones to make the cluster work
postgresql:
parameters:
max_worker_processes: "60"
pg_hba:
# To access through TCP/IP you will need to get username
# and password from the secret cluster-example-custom-app
- host all all all md5
# Example of rolling update strategy:
# - unsupervised: automated update of the primary once all
# replicas have been upgraded (default)
# - supervised: requires manual supervision to perform
# the switchover of the primary
primaryUpdateStrategy: unsupervised
# Require 1Gi of space per instance using default storage class
storage:
size: 1Gi
postgresql セクション
ポッド内のPostgreSQLインスタンスは、デフォルトのpostgresql.conf
ファイルで始まり、これらの設定が自動的に追加されます。
listen_addresses = *
include custom.conf
custom.conf ファイルには、次の例にあるように、postgresql
セクションのユーザー定義設定が含まれます。
# ...
postgresql:
parameters:
shared_buffers: "1GB"
# ...
参考
GUC Grand Unified Configurationとしても知られる more information on the available parameters のPostgreSQLドキュメントを参照してください。 CloudNativePGはPostgreSQLパラメーターの文字列のみを受け入れることに注意してください。
custom.conf
のコンテンツは、次のセクションをこの順序で適用することにより、オペレーターによって自動的に生成および維持されます。
グローバルデフォルトパラメーター
PostgreSQLメジャーバージョンに依存するデフォルトパラメーター
ユーザー指定パラメーター
固定パラメーター
グローバルデフォルトパラメーター は次のとおりです。
archive_timeout = 5min
dynamic_shared_memory_type = posix
full_page_writes = on
logging_collector = on
log_destination = csvlog
log_directory = /controller/log
log_filename = postgres
log_rotation_age = 0
log_rotation_size = 0
log_truncate_on_rotation = false
max_parallel_workers = 32
max_replication_slots = 32
max_worker_processes = 32
shared_memory_type = mmap
shared_preload_libraries =
ssl_max_protocol_version = TLSv1.3
ssl_min_protocol_version = TLSv1.3
wal_keep_size = 512MB
wal_level = logical
wal_log_hints = on
wal_sender_timeout = 5s
wal_receiver_timeout = 5s
警告
PostgreSQLクラスターでのWALセグメント保持を計画し、予想および観察されたワークロードに基づいて、サーバーバージョンに応じて`wal_keep_size` または`wal_keep_segments` を適切に構成するのはあなたの義務です。
また、唯一のストリーミングレプリケーションクライアントが高可用性クラスターで実行されているレプリカインスタンスである場合、クラスターレベルでレプリケーションスロットのサポートを追加するレプリケーションスロット機能を利用できます。
replicationSlots.highAvailability
オプションを使用して機能を有効にできます。詳細については、
レプリケーションユーザーについて を参照してください。
レプリケーションスロットも継続的バックアップも設定されていない場合、
wal_keep_size またはwal_keep_segments
の構成がスタンバイを同期外れから保護する唯一の方法です。スタンバイが同期から外れると、"could not receive data from WAL stream: ERROR: requested WAL segment **** **** **** **** **** **** has already been removed"
のようなエラーメッセージが生成されます。これには、 PGDATA
の一部、またはWALファイルの保存専用のボリュームを専用にして、ストリーミングレプリケーションの目的で古いWALセグメントを保持する必要があります。
次のパラメーターは 固定 で、オペレーターによって排他的に制御されます。
archive_command = /controller/manager wal-archive %p
hot_standby = true
listen_addresses = *
port = 5432
restart_after_crash = false
ssl = on
ssl_ca_file = /controller/certificates/client-ca.crt
ssl_cert_file = /controller/certificates/server.crt
ssl_key_file = /controller/certificates/server.key
unix_socket_directories = /controller/run
固定パラメーターは最後に追加されるため、ユーザーがYAML構成を介してオーバーライドすることはできません。これらのパラメーターは、正しいWALアーカイブとレプリケーションに必要です。
先行書き込みログレベル
PostgreSQLのパラメーターは、先行書き込みログWALに書き込まれる情報の量を決定します。次の値を受け入れます。
minimalクラッシュリカバリーに必要な情報のみを書き込みます。replicaスタンバイインスタンスで読み取り専用クエリを実行する機能など、WALアーカイブとストリーミングレプリケーションをサポートするための十分な情報を追加します。logicalreplicaからのすべての情報に加えて、論理デコードとレプリケーションに必要な追加情報が含まれます。
デフォルトでは、上流のPostgreSQLはwal_level をreplica
に設定します。 CloudNativePGは、代わりに、デフォルトでwal_level
をlogical
に設定して、すぐに論理レプリケーションを有効にします。これにより、外部のPostgreSQLサーバーからの移行などのユースケースのサポートが簡単になります。
クラスターが論理レプリケーションを必要としない場合は、wal_level
をreplica
に設定して、WALボリュームとオーバーヘッドを削減することをお勧めします。
最後に、CloudNativePGでは、WALアーカイブが無効になっているシングルインスタンスクラスターに限り、
wal_level をminimal に設定できます。
レプリケーション設定
primary_conninfo 、restore_command
、およびrecovery_target_timeline
パラメーターは、クラスター内のインスタンスのロールに基づいて、オペレーターによって自動的に管理されます。これらのパラメーターは、インスタンスがレプリカとして動作している場合にのみ有効に適用されます。
primary_conninfo = host=<PRIMARY> user=postgres dbname=postgres
recovery_target_timeline = latest
STANDBY_TCP_USER_TIMEOUT
が指定されている場合、オペレーターによって管理されているすべてのスタンバイインスタンスにtcp_user_timeout
パラメーターを設定します。
tcp_user_timeout
パラメーターは、TCP接続が強制的にクローズされるまでに、送信データが未確認のままでいられる時間を決定します。この値を調整すると、ネットワークの中断に対するスタンバイインスタンスの応答性を微調整できます。詳細については、
PostgreSQL documentation を参照してください。
ログ制御設定
オペレーターは、CSV形式でログを出力するためにPostgreSQLを必要とし、インスタンスマネージャーは自動的にそれを解析し、JSON形式で出力します。このため、PostgreSQLのすべてのログ設定は固定され、変更できません。
詳細については、 ロギング を参照してください。
共有プリロードライブラリ
PostgreSQLのshared_preload_libraries
オプションは、サーバー起動時にコンマ区切りリストの形式でプリロードされる1つ以上の共有ライブラリを指定するために存在します。通常、PostgreSQLで使用され、システム全体のほとんどのデータベースセッションで使用する必要がある拡張機能がロードされますpg_stat_statements
など。
CloudNativePGでは、shared_preload_libraries
オプションはデフォルトで空です。 shared_preload_libraries
のコンテンツをオーバーライドすることはできますが、熟練したPostgresユーザーのみがこのオプションを利用することをお勧めします。
重要
指定されたライブラリが見つからない場合、サーバーは起動に失敗し、CloudNativePGの自己修復の試行を妨げ、手動介入が必要になります。コンテンツを直接管理する予定がある場合は、 shared_preload_libraries の拡張機能と設定の両方を常にテストしてください。
CloudNativePGは、最も使用される一部のPostgreSQL拡張機能のshared_preload_libraries
オプションのコンテンツを自動的に管理できます。詳細については、以下の マネージド拡張機能 セクションを参照してください。
具体的には、構成パラメーターに管理ライブラリのいずれかが必要であることにオペレーターが気づくと、必要なライブラリが自動的に追加されます。オペレーターは、実際のパラメーターが必要としないとすぐにライブラリを削除します。
重要
shared_preload_libraries からライブラリを削除するには、クラスター内のすべてのインスタンスを再起動する必要があることに常に注意してください。
文字列のリストとして、.spec.postgresql.shared_preload_libraries
を介して追加のshared_preload_libraries
を提供できます。オペレーターは、それらを自動的に管理するものとマージします。
マネージド拡張機能
前のセクションで予想されたように、CloudNativePGは、一部のよく知られサポートされている拡張機能のshared_preload_libraries
のコンテンツを自動的に管理します。現在のリストには以下が含まれます。
auto_explainpg_stat_statementspgauditpg_failover_slots
これらのライブラリの一部は、使用する前にデータベース内の追加オブジェクトも必要とします。通常は、データベースで実行するCREATE EXTENSION
コマンドを介して管理されるビューおよび/またはファンクションです。通常、DROP EXTENSION
コマンドはこれらのオブジェクトを削除します。
このようなライブラリの場合、CloudNativePGは、次のクエリーで識別されるクラスター内の接続を受け入れるすべてのデータベースでの拡張機能の作成と削除を自動的に処理します。
SELECT datname FROM pg_database WHERE datallowconn
注釈
上記のクエリーには、template1 のようなテンプレートデータベースも含まれています。
重要
declarative extensions の導入により
Database
CRDでは、拡張機能を直接管理できるようになりました。その結果、マネージド拡張機能はCloudNativePGの将来のバージョンで重要な変更が発生する可能性があり、一部の機能は非推奨になる可能性があります。
auto_explain の有効化
拡張機能は、 EXPLAIN
を手動で実行することなく、遅いステートメントの実行プランを自動的にログに記録する手段を提供します最適化されていないクエリーを追跡するのに役立ちます。
次の抜粋例のようにauto_explain.
で始まるパラメーターを構成に追加することにより、auto_explain
を有効にできます。完了までに10秒以上かかるクエリの実行プランを自動的にログに記録します。
# ...
postgresql:
parameters:
auto_explain.log_min_duration: "10s"
# ...
注釈
auto_explainを有効にすると、パフォーマンスの問題が発生する可能性があります。 the auto explain documentation を参照してください。
pg_stat_statements の有効化
拡張機能は、クエリのリアルタイムモニタリングのためにPostgreSQLで使用可能な最も重要な機能の1つです。
次の例の抜粋のように、pg_stat_statements.
で始まるパラメーターを構成に追加することにより、pg_stat_statements
を有効にできます。
# ...
postgresql:
parameters:
pg_stat_statements.max: "10000"
pg_stat_statements.track: all
# ...
前述のように、オペレーターはpg_stat_statements
をshared_preload_libraries
に自動的に追加し、各データベースでCREATE EXTENSION IF NOT EXISTS pg_stat_statements
を実行します。これにより、 pg_stat_statements
ビューに対してクエリーを実行できます。
pgaudit の有効化
pgaudit
拡張機能は、標準のPostgreSQLロギング機能を介して詳細なセッションおよび/またはオブジェクト監査ログを提供します。
CloudNativePGは、PostgreSQLクラスターで PGAudit の透過的かつネイティブサポートを備えています。詳細については、 PG監査ログ を参照してください。
次の例の抜粋のように、pgaudit.
で始まるパラメーターを構成に追加することにより、pgaudit
を有効にできます。
#
postgresql:
parameters:
pgaudit.log: "all, -misc"
pgaudit.log_catalog: "off"
pgaudit.log_parameter: "on"
pgaudit.log_relation: "on"
#
#### Enabling `pg_failover_slots`
The [`pg_failover_slots`](https://github.com/EnterpriseDB/pg_failover_slots)
extension by EDB ensures that logical replication slots can survive a
failover scenario. Failovers are normally implemented using physical
streaming replication, like in the case of CloudNativePG.
You can enable `pg_failover_slots` by adding to the configuration a parameter
that starts with `pg_failover_slots.`: as explained above, the operator will
transparently manage the `pg_failover_slots` entry in the
`shared_preload_libraries` option depending on this.
Please refer to [`the `pg_failover_slots` documentation`](https://www.enterprisedb.com/docs/pg_extensions/pg_failover_slots)
for details on this extension.
Additionally, for each database that you intend to you use with `pg_failover_slots`
you need to add an entry in the `pg_hba` section that enables each replica to
connect to the primary.
For example, suppose that you want to use the `app` database with `pg_failover_slots`,
you need to add this entry in the `pg_hba` section:
``` yaml postgresql: pg_hba: - hostssl appstreaming_replica all cert
The pg_hba section
pg_hba is a list of PostgreSQL Host Based Authentication rules used
to create the pg_hba.conf used by the pods.
!!! Important See the PostgreSQL documentation for more information on ``pg_hba.conf` <https://www.postgresql.org/docs/current/auth-pg-hba-conf.html>`__.
Since the first matching rule is used for authentication, the
pg_hba.conf file generated by the operator can be seen as composed
of four sections:
Fixed rules
User-defined rules
Optional LDAP section
Default rules
Fixed rules:
``` テキストローカル すべて すべて ピア
hostssl postgresstreaming_replica all cert map=cnpg_streaming_replica hostssl replication stable_replica all cert map=cnpg_streaming_replica hostssl all cnpg_pooler_pgbouncer all cert map=cnpg_pooler_pgbouncer
Default rules:
``` text host all all all <default-authentication-method>
From PostgreSQL 14 the default value of the password_encryption
database parameter is set to scram-sha-256. Because of that, the
default authentication method is scram-sha-256 from this PostgreSQL
version.
PostgreSQL 13 and older will use md5 as the default authentication
method.
The resulting pg_hba.conf will look like this:
``` テキストローカル すべて すべて ピア
hostssl postgresstreaming_replica all cert map=cnpg_streaming_replica hostssl replication stable_replica all cert map=cnpg_streaming_replica hostssl all cnpg_pooler_pgbouncer all cert map=cnpg_pooler_pgbouncer
host all all all scram-sha-256 #またはPostgreSQLバージョン<= 13の場合はmd5
edb_notranlate_13 yaml postgresql: pg_hba: - hostssl app app 10.244.0.0/16 md5
In the above example we are enabling access for the `app` user to the `app`
database using MD5 password authentication (you can use `scram-sha-256`
if you prefer) via a secure channel (`hostssl`).
### LDAP Configuration
Under the `postgres` section of the cluster spec there is an optional `ldap` section available to define an LDAP
configuration to be converted into a rule added into the `pg_hba.conf` file.
This will support two modes: `simple bind` mode which requires specifying a `server`, `prefix` and `suffix` in the LDAP
section and the `search+bind` mode which requires specifying `server`, `baseDN`, `binDN`, and a `bindPassword` which is
a secret containing the ldap password. Additionally, in `search+bind` mode you have the option to specify a
`searchFilter` or `searchAttribute`. If no `searchAttribute` is specified the default one of `uid` will be used.
Additionally, both modes allow the specification of a `scheme` for ldapscheme and a `port`. Neither scheme nor port are
required, however.
This section filled out for search+bind could look as follows:
``` yaml postgresql: ldap: server: 'openldap.default.svc.cluster.local'bindSearchAuth:baseDN: 'ou=org,dc=example,dc=com'bindDN: 'cn=admin,dc=example,dc=com 'bindPassword: name: 'ldapBindPassword' key: 'data' searchAttribute: 'uid'
The pg_ident section
pg_ident is a list of PostgreSQL User Name Maps that CloudNativePG
uses to generate and maintain the ident map file (known as
pg_ident.conf) inside the data directory.
!!! Important See the PostgreSQL documentation for more information on ``pg_ident.conf` <https://www.postgresql.org/docs/current/auth-username-maps.html>`__.
The pg_ident.conf file written by the operator is made up of the
following two sections:
Fixed rules
User-defined rules
Currently the only fixed rule, automatically generated by the operator, is:
``` text local postgres
The instance manager detects the user running the PostgreSQL instance and
automatically adds a rule to map it to the `postgres` user in the database.
If the `postgres` user is not properly configured inside the container, the
instance manager will allow any local user to connect and then log a warning
message like the following:
``` text 現在のユーザーを識別できません。安全でないマッピングへのフォールバック。
The resulting pg_ident.conf will look like this:
``` text local postgres
edb_notranlate_18 yaml postgresql: pg_ident: - “mymap /^(.*)@mydomain\.com$ \1”
## Changing configuration
You can apply configuration changes by editing the `postgresql` section of
the `Cluster` resource.
After the change, the cluster instances will immediately reload the
configuration to apply the changes.
If the change involves a parameter requiring a restart, the operator will
perform a rolling upgrade.
## Enabling `ALTER SYSTEM`
CloudNativePG strongly advocates employing the Cluster manifest as the
exclusive method for altering the configuration of a PostgreSQL cluster. This
approach guarantees coherence across the entire high-availability cluster and
aligns with best practices for Infrastructure-as-Code.
In CloudNativePG the default configuration disables the use of `ALTER SYSTEM`
on new Postgres clusters. This decision is rooted in the recognition of
potential risks associated with this command. To enable the use of `ALTER SYSTEM`,
you can explicitly set `.spec.postgresql.enableAlterSystem` to `true`.
!!! Warning
Proceed with caution when utilizing `ALTER SYSTEM`. This command operates
directly on the connected instance and does not undergo replication.
CloudNativePG assumes responsibility for certain fixed parameters and complete
control over others, emphasizing the need for careful consideration.
Starting from PostgreSQL 17, the `.spec.postgresql.enableAlterSystem` setting
directly controls the [`allow_alter_system` GUC in PostgreSQL](https://www.postgresql.org/docs/17/runtime-config-compatible.html#GUC-ALLOW-ALTER-SYSTEM)
— a feature directly contributed by CloudNativePG to PostgreSQL.
Prior to PostgreSQL 17, when `.spec.postgresql.enableAlterSystem` is set to
`false`, the `postgresql.auto.conf` file is made read-only. Consequently, any
attempt to execute the `ALTER SYSTEM` command will result in an error. The
error message might look like this:
```出力エラー ファイル"postgresql.auto.conf"を開くことができませんでした。アクセスが拒否されました
固定パラメーター
一部のPostgreSQL構成パラメーターは、オペレーターが排他的に管理する必要があります。オペレーターは、ユーザーがWebhookを使用してそれらを設定できないようにします。
ユーザーはpostgresql
セクションで次の構成パラメーターを設定することはできません。
allow_alter_systemallow_system_table_modsarchive_cleanup_commandarchive_commandarchive_modebonjourbonjour_namecluster_nameconfig_filedata_directorydata_sync_retryevent_sourceexternal_pid_filehba_filehot_standbyident_filejit_providerlisten_addresseslog_destinationlog_directorylog_file_modelog_filenamelog_rotation_agelog_rotation_sizelog_truncate_on_rotationlogging_collectorportprimary_conninfoprimary_slot_namepromote_trigger_filerecovery_end_commandrecovery_min_apply_delayrecovery_targetrecovery_target_actionrecovery_target_inclusiverecovery_target_lsnrecovery_target_namerecovery_target_timerecovery_target_timelinerecovery_target_xidrestart_after_crashrestore_commandshared_preload_librariessslssl_ca_filessl_cert_filessl_crl_filessl_dh_params_filessl_ecdh_curvessl_key_filessl_passphrase_commandssl_passphrase_command_supports_reloadssl_prefer_server_ciphersstats_temp_directorysynchronous_standby_namessyslog_facilitysyslog_identsyslog_sequence_numberssyslog_split_messagesunix_socket_directoriesunix_socket_groupunix_socket_permissions