# Use PG as Prometheus Backend

> Persist prometheus metrics with PostgreSQL + TimescaleDB through Promscale
---

It is not recommended to use PostgreSQL as a backend for Prometheus, but it is a good opportunity to understand the
Pigsty deployment system.


------

## Postgres Preparation

```bash
vi pigsty.yml # dbuser_prometheus  prometheus

pg_databases:                           # define business users/roles on this cluster, array of user definition
  - { name: prometheus, owner: dbuser_prometheus , revokeconn: true, comment: prometheus primary database }
pg_users:                           # define business users/roles on this cluster, array of user definition
  - {name: dbuser_prometheus , password: DBUser.Prometheus ,pgbouncer: true , createrole: true,  roles: [dbrole_admin], comment: admin user for prometheus database }
```

Create the database and user:

```bash
bin/pgsql-user  pg-meta  dbuser_prometheus
bin/pgsql-db    pg-meta  prometheus
```

Check the connection string:

```bash
psql postgres://dbuser_prometheus:DBUser.Prometheus@10.10.10.10:5432/prometheus -c 'CREATE EXTENSION timescaledb;'
```

------

## Promscale Configuration

Install promscale package:

```bash
yum install -y promscale
```

If the package is not available in the default repository, you can download it directly:

```bash
wget https://github.com/timescale/promscale/releases/download/0.6.1/promscale_0.6.1_Linux_x86_64.rpm
sudo rpm -ivh promscale_0.6.1_Linux_x86_64.rpm
```

Edit the `promscale` configuration file `/etc/sysconfig/promscale.conf`

```bash
PROMSCALE_DB_HOST="127.0.0.1"
PROMSCALE_DB_NAME="prometheus"
PROMSCALE_DB_PASSWORD="DBUser.Prometheus"
PROMSCALE_DB_PORT="5432"
PROMSCALE_DB_SSL_MODE="disable"
PROMSCALE_DB_USER="dbuser_prometheus"
```

Launch promscale service, it will create schema in `prometheus` database.

```bash
# launch
cat /usr/lib/systemd/system/promscale.service
systemctl start promscale && systemctl status promscale
```

------

## Prometheus Configuration

Prometheus can use Remote Write/ Remote Read to store metrics in Postgres via Promscale.

Edit the Prometheus configuration file:

```bash
vi /etc/prometheus/prometheus.yml
```

Add the following configuration to the `remote_write` and `remote_read` sections:

```yaml
remote_write:
  - url: "http://127.0.0.1:9201/write"
remote_read:
  - url: "http://127.0.0.1:9201/read"
```

Metrics are loaded into Postgres after Prometheus is restarted.

```bash
systemctl restart prometheus
```
