Connecting from an application

Applications are supposed to work with the services created by CloudNativePGin the same Kubernetes cluster:

  • [cluster name]-rw

  • [cluster name]-ro

  • [cluster name]-r

Those services are entirely managed by the Kubernetes cluster andimplement a form of Virtual IP as described in the Exposing Postgres Services .

Hint

It is highly recommended using those services in your applications, and avoiding connecting directly to a specific PostgreSQL instance, as the latter can change during the cluster lifetime.

You can use these services in your applications through:

  • DNS resolution

  • environment variables

For the credentials to connect to PostgreSQL, you canuse the secrets generated by the operator.

Warning

The operator will create another service, named [cluster name]-any . That service is used internally to manage PostgreSQL instance discovery. It’s not supposed to be used directly by applications.

DNS resolution

You can use the Kubernetes DNS service to point to a given server.The Kubernetes DNS service is required by the operator.You can do that by using the name of the service if the application isdeployed in the same namespace as the PostgreSQL cluster.In case the PostgreSQL cluster resides in a different namespace, you can use thefull qualifier: service-name.namespace-name .

DNS is the preferred and recommended discovery method.

Environment variables

If you deploy your application in the same namespace that contains thePostgreSQL cluster, you can also use environment variables to connect to the database.

For example, suppose that your PostgreSQL cluster is called pg-database ,you can use the following environment variables in your applications:

Secrets

The PostgreSQL operator will generate two basic-auth type secrets for everyPostgreSQL cluster it deploys:

  • [cluster name]-superuser

  • [cluster name]-app

The secrets contain the username, password, and a working .pgpass file respectively for the postgres user and the owner of the database.

The -app credentials are the ones that should be used by applicationsconnecting to the PostgreSQL cluster.

The -superuser ones are supposed to be used only for administrative purposes.