postgresql-ha-chart

by SolDevelo

Helm chartv16.3.4App 17.6.0

This PostgreSQL cluster solution includes the PostgreSQL replication manager, an open-source tool for managing replication and failover on PostgreSQL clusters.

About this chart

SolDevelo PostgreSQL HA Helm chart

This PostgreSQL cluster solution includes the PostgreSQL replication manager, an open-source tool for managing replication and failover on PostgreSQL clusters.

Overview of PostgreSQL HA

This chart is a fork of the Bitnami PostgreSQL HA chart, maintained by SolDevelo and configured to use SolDevelo container images.

TL;DR

helm install my-release oci://registry-1.docker.io/soldevelo/postgresql-ha-chart

Introduction

This Helm chart installs PostgreSQL with HA architecture in a Kubernetes cluster. Welcome to contribute to Helm Chart for PostgreSQL HA.

This Helm chart has been developed based on bitnami/postgresql chart but including some changes to guarantee high availability such as:

  • A new deployment, service have been added to deploy Pgpool-II to act as proxy for PostgreSQL backend. It helps to reduce connection overhead, acts as a load balancer for PostgreSQL, and ensures database node failover.
  • Replacing bitnami/postgresql with bitnami/postgresql-repmgr which includes and configures repmgr. Repmgr ensures standby nodes assume the primary role when the primary node is unhealthy.

Differences between the PostgreSQL-HA and PostgreSQL Helm charts

There are two different ways to deploy a PostgreSQL cluster, using the PostgreSQL Helm chart or the PostgreSQL High Availability (HA) Helm chart. Both solutions provide a simple and reliable way to run PostgreSQL in a production environment. Keep reading to discover the differences between them and check which one better suits your needs.

  • Both the PostgreSQL HA and the PostgreSQL chart configures a cluster with a primary/replica topology. The primary node has writing permissions while replication is on the replica nodes which have read-only permissions.
  • The PostgreSQL HA Helm chart deploys a cluster with four nodes by default, one for Pgpool-II, and three PostgreSQL+Repmgr replicas. The PostgreSQL chart configures a cluster with two nodes by default (one primary and one replica).
  • The PostgreSQL HA Helm chart uses Pgpool-II to handle the connection to the nodes. Pgpool-II is responsible to spread the queries among nodes.
  • The PostgreSQL HA Helm chart includes a Repmgr module that ensures high-availability thanks to automatic membership control. If the primary is down, any of the replica nodes will be promoted as primary to avoid data loss.

The following diagram shows you the options you have for using Bitnami's PostgreSQL solutions in your deployments:

Prerequisites

  • Kubernetes 1.23+
  • Helm 3.8.0+

Installing the Chart

To install the chart with the release name my-release:

helm install my-release oci://REGISTRY_NAME/REPOSITORY_NAME/postgresql-ha-chart

Note: You need to substitute the placeholders REGISTRY_NAME and REPOSITORY_NAME with a reference to your Helm chart registry and repository. For example, for SolDevelo use REGISTRY_NAME=registry-1.docker.io and REPOSITORY_NAME=soldevelo.

Configuration and installation details

Resource requests and limits

Bitnami charts allow setting resource requests and limits for all containers inside the chart deployment. These are inside the resources value (check parameter table). Setting requests is essential for production workloads and these should be adapted to your specific use case.

To make this process easier, the chart contains the resourcesPreset values, which automatically sets the resources section according to different presets. Check these presets in the bitnami/common chart. However, in production workloads using resourcesPreset is discouraged as it may not fully adapt to your specific needs. Find more information on container resource management in the official Kubernetes documentation.

Prometheus metrics

This chart can be integrated with Prometheus by setting metrics.enabled to true. This will deploy a sidecar container with postgres_exporter in all pods. It will also create metrics services that can be configured under the metrics.service section. These services will be have the necessary annotations to be automatically scraped by Prometheus.

Prometheus requirements

It is necessary to have a working installation of Prometheus or Prometheus Operator for the integration to work. Install the Bitnami Prometheus helm chart or the Bitnami Kube Prometheus helm chart to easily have a working Prometheus in your cluster.

Integration with Prometheus Operator

The chart can deploy ServiceMonitor objects for integration with Prometheus Operator installations. To do so, set the value metrics.serviceMonitor.enabled=true. Ensure that the Prometheus Operator CustomResourceDefinitions are installed in the cluster or it will fail with the following error:

no matches for kind "ServiceMonitor" in version "monitoring.coreos.com/v1"

Install the Bitnami Kube Prometheus helm chart for having the necessary CRDs and the Prometheus Operator.

Update credentials

Bitnami charts configure credentials at first boot. Any further change in the secrets or credentials require manual intervention. Follow these instructions:

  • Update the user password following the upstream documentation
  • Update the password secret with the new values (replace the SECRET_NAME, POSTGRES_PASSWORD and PASSWORD and REPMGR_PASSWORD placeholders)
kubectl create secret generic SECRET_NAME --from-literal=postgres-password=POSTGRES_PASSWORD --from-literal=password=PASSWORD --from-literal=repmgr-password=REPMGR_PASSWORD --dry-run -o yaml | kubectl apply -f -

Rolling VS Immutable tags

It is strongly recommended to use immutable tags in a production environment. This ensures your deployment does not change automatically if the same tag is updated with a different image.

Bitnami will release a new chart updating its containers if a new version of the main container, significant changes, or critical vulnerabilities exist.

Use a different PostgreSQL version

To modify the application version used in this chart, specify a different version of the image using the postgresql.image.tag parameter and/or a different repository using the postgresql.image.repository parameter.

Use a volume for /dev/shm

When working with huge databeses, /dev/shm can run out of space. A way to fix this is to use the postgresql.extraVolumes and postgresql.extraVolumeMounts values. In the example below, we set an emptyDir volume with 512Mb:

postgresql:
  extraVolumes:
    - name: dshm
      emptyDir:
        medium: Memory
        sizeLimit: 512Mi
  extraVolumeMounts:
    - name: dshm
      mountPath: /dev/shm

Configure the way how to expose Pgpool-II

  • ClusterIP: Exposes the service on a cluster-internal IP. Choosing this value makes the service only reachable from within the cluster. Set service.type=ClusterIP to choose this service type.
  • NodePort: Exposes the service on each Node's IP at a static port (the NodePort). You will be able to contact the NodePort service, from outside the cluster, by requesting NodeIP:NodePort. Set service.type=NodePort to choose this service type.
  • LoadBalancer: Exposes the service externally using a cloud provider's load balancer. Set service.type=LoadBalancer to choose this service type.

Adjust permissions of persistent volume mountpoint

As the images run as non-root by default, it is necessary to adjust the ownership of the persistent volumes so that the containers can write data into it.

By default, the chart is configured to use Kubernetes Security Context to automatically change the ownership of the volume. However, this feature does not work in all Kubernetes distributions. As an alternative, this chart supports using an initContainer to change the ownership of the volume before mounting it in the final destination.

You can enable this initContainer by setting volumePermissions.enabled to true.

LDAP

LDAP support can be enabled in the chart by specifying the ldap. parameters while creating a release. The following parameters should be configured to properly enable the LDAP support in the chart.

  • ldap.enabled: Enable LDAP support. Defaults to false.
  • ldap.uri: LDAP URL beginning in the form ldap[s]://<hostname>:<port>. No defaults.
  • ldap.basedn: LDAP base DN. No defaults.
  • ldap.binddn: LDAP bind DN. No defaults.
  • ldap.bindpw: LDAP bind password. No defaults.
  • ldap.bslookup: LDAP base lookup. No defaults.
  • ldap.nss_initgroups_ignoreusers: LDAP ignored users. root,nslcd.
  • ldap.scope: LDAP search scope. No defaults.
  • ldap.searchfilter: LDAP search filter. No defaults.
  • ldap.searchmap: LDAP search map. No defaults.
  • ldap.tls_reqcert: LDAP TLS check on server certificates. No defaults.

For example:

ldap.enabled="true"
ldap.uri="ldap://my_ldap_server"
ldap.basedn="dc=example\,dc=org"
ldap.binddn="cn=admin\,dc=example\,dc=org"
ldap.bindpw="admin"
ldap.bslookup="ou=group-ok\,dc=example\,dc=org"
ldap.nss_initgroups_ignoreusers="root\,nslcd"
ldap.scope="sub"
ldap.searchfilter="posixaccount"
ldap.searchmap="uid"
ldap.tls_reqcert="demand"

Next, login to the PostgreSQL server using the psql client and add the PAM authenticated LDAP users.

Note: Parameters including commas must be escaped as shown in the above example.

Securing traffic using TLS

The chart handles two main flows of traffic information:

  • Connections between end-clients and Pgpool-II (sometimes referred to as frontend connections).
  • Internal connections between Pgpool-II and PostgreSQL nodes (sometimes referred to as backend connections).

The Bitnami postgresql-ha chart allows configuring the securitization of both types of traffic using TLS.

Encrypt traffic between clients and Pgpool-II (frontend)

TLS for end-client connections can be enabled in the chart by specifying the pgpool.tls.* parameters when installing a release. Below you can find detailed information about these parameters:

  • pgpool.tls.enabled: Enable TLS support. Defaults to false.
  • pgpool.tls.certificatesSecret: Name of an existing secret that contains the certificates. No defaults.
  • pgpool.tls.certFilename: Certificate filename. No defaults.
  • pgpool.tls.certKeyFilename: Certificate key filename. No defaults.

For example:

  • First, create a secret with the certificates files. You will need to generate previously the certificate files:

    kubectl create secret generic pgpool-tls-secret --from-file=./cert.crt --from-file=./cert.key --from-file=./ca.crt
    

Note: Although certificate generation is out of the scope of this guide, bear in mind that PostgreSQL requires that server TLS certificates specify the actual DNS server name in the CN (Common Name) field.

  • Then, install the chart using the following parameters:

    pgpool.tls.enabled=true
    pgpool.tls.certificatesSecret="pgpool-tls-secret"
    pgpool.tls.certFilename="cert.crt"
    pgpool.tls.certKeyFilename="cert.key"
    

Note: Certificates permissions: Pgpool-II requires certain permissions on sensitive files (such as certificate keys) to start up. Due to an on-going issue regarding K8s permissions and the use of containerSecurityContext.runAsUser, an init container will adapt the permissions to ensure everything works as expected.

Enable client certificate authentication

When TLS is configured for frontend connections, the server can be configured to authenticate clients by verifying their provided TLS certificate is valid and trusted. Hence, the client will not be sent a password prompt.

You can enable this authentication feature additionally specifying the following parameter:

  • postgresql.tls.certCAFilename: CA Certificate filename. No defaults.

    $ psql --host postgresql-ha-pgpool -d "dbname=XXXXX user=YYYYYY sslcert=client.crt sslkey=client.key sslmode=require"
    psql (14.4)
    SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
    Type "help" for help.
    
    postgres=>
    

Clients using this method to authenticate will be required to provide a certificate with the CN (Common Name) field matching the requested database user name. Please, refer to the official documentation for further information.

Note: As with traditional password-based authentication, database users must exist in both Pgpool-II and PostgreSQL nodes and have the correct privileges to connect to a database. You may use the postgresql.initdbScripts and pgpool.customUsers properties to create them in advance.

Encrypt traffic between Pgpool-II and PostgreSQL no

Deploy postgresql-ha-chart with OpenTenant

Each tenant gets its own release of this chart, with its own namespace, secrets and domain. The builder below already has postgresql-ha-chart on a Hetzner server. Change the host, add apps from the marketplace, then copy the generated files. Providers and prices are samples, and nothing here is sent anywhere.

  1. Pick a serverConnect Hetzner, OVHcloud or AWS. The builder starts on Hetzner, the cheapest sample rate.
  2. Place the chartpostgresql-ha-chart is pinned at v16.3.4 in opentenant.yaml. Drag more apps from the marketplace onto a rack.
  3. ApplySave opentenant.yaml and main.tf from the console, then run the commands below.
# opentenant.yaml, main.tf and dns.tf come from the builder below
opentenant validate opentenant.yaml
terraform init && terraform apply