<br />

This document describes how to configure your Google Kubernetes Engine deployment
so that you can use Google Cloud Managed Service for Prometheus to collect metrics from

PostgreSQL. This document shows you how to do the following:

- Set up the exporter for PostgreSQL to report metrics.
- Access a predefined dashboard in Cloud Monitoring to view the metrics.
- Configure alerting rules to monitor the metrics.

<br />

These instructions apply only if you are using [managed collection](https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/setup-managed.md.txt)
with Managed Service for Prometheus.
If you are using self-deployed collection, then see the

[source repository](https://github.com/prometheus-community/postgres_exporter)
for the PostgreSQL exporter

for installation information.

These instructions are provided as an example and are expected to work in
most Kubernetes environments.

If you are having trouble installing an
application or exporter due to restrictive security or organizational policies,
then we recommend you consult open-source documentation for support.

For information about PostgreSQL, see [PostgreSQL](https://www.postgresql.org/).

## Prerequisites

To collect metrics from

PostgreSQL

by using
Managed Service for Prometheus and managed collection, your deployment must
meet the following requirements:

- Your cluster must be running Google Kubernetes Engine version 1.28.15-gke.2475000 or later.
- You must be running Managed Service for Prometheus with managed collection enabled. For more information, see [Get started with managed collection](https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/setup-managed.md.txt).

  <br />

- To use dashboards available in Cloud Monitoring for the PostgreSQL integration, you must use `postgres_exporter` version v0.11.1 or later.

  For more information about available dashboards, see

  [View dashboards](https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/exporters/postgresql.md.txt#monitoring-dashboard).

<br />

For information about creating a least-privileged user, see [Running as non-superuser](https://github.com/prometheus-community/postgres_exporter#running-as-non-superuser).

## Install the PostgreSQL exporter

We recommend that you install the PostgreSQL exporter,
[`postgres_exporter`](https://github.com/prometheus-community/postgres_exporter),
as a sidecar to your PostgreSQL workload.
For information about using sidecars, see
[Extended applications on Kubernetes with multi-container
pods](https://learnk8s.io/sidecar-containers-patterns).

To install `postgres_exporter` as a sidecar to PostgreSQL,
modify your PostgreSQL configuration as shown in the following
example:

```postgresql
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: postgresql
spec:
  serviceName: postgresql
  selector:
    matchLabels:
+     app.kubernetes.io/name: postgresql
  template:
    metadata:
      labels:
+       app.kubernetes.io/name: postgresql
    spec:
      containers:
      - image: postgres:15.3
        name: postgresql
        env:
        - name: POSTGRES_USER
          value: root
        - name: POSTGRES_PASSWORD
          value: password
        - name: POSTGRES_DB
          value: dev
+     - name: exporter
+       image: quay.io/prometheuscommunity/postgres-exporter:v0.14.0
+       args:
+         - --collector.stat_statements
+       env:
+       - name: DATA_SOURCE_NAME
+         value: postgresql://root:password@localhost:5432/dev?sslmode=disable
+       ports:
+       - containerPort: 9187
+         name: prometheus
```

You must add any lines preceded by the `+` symbol to your
configuration.
Update the `DATA_SOURCE_NAME` environment variable with credentials that work with your PostgreSQL instance.

To apply configuration changes from a local file, run the following command:

```
kubectl apply -n NAMESPACE_NAME -f FILE_NAME
```

<br />

You can also
[use Terraform](https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/setup-managed.md.txt#terraform-scrape)
to manage your configurations.

## Define a PodMonitoring resource

For target discovery, the Managed Service for Prometheus Operator
requires a PodMonitoring resource that corresponds to
the PostgreSQL exporter in the same namespace.

You can use the following PodMonitoring configuration:

```yaml
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: monitoring.googleapis.com/v1
kind: PodMonitoring
metadata:
  name: postgresql
  labels:
    app.kubernetes.io/name: postgresql
    app.kubernetes.io/part-of: google-cloud-managed-prometheus
spec:
  endpoints:
  - port: prometheus
    scheme: http
    interval: 30s
    path: /metrics
  selector:
    matchLabels:
      app.kubernetes.io/name: postgresql
```

Ensure that the label selectors and the port match the selectors and port
used in
[Install the PostgreSQL exporter](https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/exporters/postgresql.md.txt#install-exporter).

To apply configuration changes from a local file, run the following command:

```
kubectl apply -n NAMESPACE_NAME -f FILE_NAME
```

<br />

You can also
[use Terraform](https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/setup-managed.md.txt#terraform-scrape)
to manage your configurations.

## Define rules and alerts

You can use the following `Rules` configuration to define
alerts on your PostgreSQL metrics:

```yaml
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: monitoring.googleapis.com/v1
kind: Rules
metadata:
  name: postgresql-rules
  labels:
    app.kubernetes.io/component: rules
    app.kubernetes.io/name: postgresql-rules
    app.kubernetes.io/part-of: google-cloud-managed-prometheus
spec:
  groups:
  - name: postgresql
    interval: 30s
    rules:
    - alert: PostgreSQLDatabaseSizeTooLarge
      annotations:
        description: |-
          PostgreSQL database size too large
            VALUE = {{ $value }}
            LABELS: {{ $labels }}
        summary: PostgreSQL database size too large (instance {{ $labels.instance }})
      expr: pg_database_size_bytes > 100000000000
      for: 5m
      labels:
        severity: warning
```

To apply configuration changes from a local file, run the following command:

```
kubectl apply -n NAMESPACE_NAME -f FILE_NAME
```

<br />

You can also
[use Terraform](https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/setup-managed.md.txt#terraform-scrape)
to manage your configurations.

For more information about applying rules to your cluster, see
[Managed rule evaluation and alerting](https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/rules-managed.md.txt).
You can adjust the alert thresholds to suit your application.

## Verify the configuration

You can use Metrics Explorer to verify that you correctly configured
the PostgreSQL exporter. It might take one or two minutes for
Cloud Monitoring to ingest your metrics.

To verify the metrics are ingested, do the following:

1. In the Google Cloud console, go to the
   **Metrics explorer** page:

   [Go to **Metrics explorer**](https://console.cloud.google.com/monitoring/metrics-explorer)

   <br />

   If you use the search bar to find this page, then select the result whose subheading is
   **Monitoring**.
2. In the toolbar of the query-builder pane, select the button whose name is **PromQL**.
3. Enter and run the following query:  

   ```
   up{job="postgresql", cluster="CLUSTER_NAME", namespace="NAMESPACE_NAME"}
   ```

<br />

## View dashboards

The Cloud Monitoring integration includes

the **PostgreSQL Prometheus Overview** dashboard.

Dashboards are automatically installed when you configure the integration.
You can also view static previews of dashboards without installing the
integration.


To view an installed dashboard, do the following:

1. In the Google Cloud console, go to the **Dashboards** page:

   [Go to **Dashboards**](https://console.cloud.google.com/monitoring/dashboards)

   <br />

   If you use the search bar to find this page, then select the result whose subheading is
   **Monitoring**.
2. Select the **Dashboard List** tab.
3. Choose the **Integrations** category.
4. Click the name of the dashboard, for example, **PostgreSQL Prometheus Overview**.

<br />

To view a static preview of the dashboard, do the following:

1. In the Google Cloud console, go to the
   ![](https://docs.cloud.google.com/static/monitoring/images/integrations-icon.png) **Integrations**
   page:

   [Go to **Integrations**](https://console.cloud.google.com/monitoring/integrations)

   <br />

   If you use the search bar to find this page, then select the result whose subheading is
   **Monitoring**.
2. Click the **Kubernetes Engine** deployment-platform filter.
3. Locate the PostgreSQL integration and click **View Details**.
4. Select the **Dashboards** tab.

<br />

## Troubleshooting

For information about troubleshooting metric ingestion problems, see
[Problems with collection from exporters](https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/troubleshooting.md.txt#exporter-problems) in [Troubleshooting ingestion-side problems](https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/troubleshooting.md.txt#ingest-problems).