# Deploy StackGres

Use `packages.experimental.stackgres-operator` and
`packages.experimental.stackgres-cluster` to run PostgreSQL under the StackGres
operator.

This guide creates one PostgreSQL 17 instance with a 5 GiB volume. The target
cluster must provide a default StorageClass, or the database instance must name
one explicitly.

## Add the StackGres operator

Install one operator instance in its own namespace:

<Snippet {...stackgresOperatorInstance} />

The operator installs and reconciles the StackGres custom resource types and
its admission webhooks when it starts. One operator manages database clusters
in every namespace, and a cluster runs only one. The package does not run the
StackGres web console, REST API, or OpenTelemetry collector.

## Add the PostgreSQL cluster

Add the database instance in the namespace where it should run:

<Snippet {...stackgresClusterInstance} />

The `stackgres-cluster` package resolves the operator through its
`stackgresOperator` dependency. Kix also connects it to the StorageClass
provided by the cluster flavor.

`postgres.version` takes a major, such as `"17"`, or a minor, such as
`"17.11"`. Kix checks it against the versions the operator's StackGres release
ships, and refuses `"latest"`, because a new operator release would then move
the database to a new major.

For a production cluster, increase `persistentVolume.size` and size
`instanceProfile` for the workload. StackGres takes CPU as whole cores or
millicores (`"2"`, `"1500m"`) and sizes in `Mi`, `Gi`, or (for the volume)
`Ti`, and Kix refuses other forms. `instances` defaults from the cluster's
availability level, and above one instance the pods spread across nodes and
zones. On a multi-node cluster StackGres also places every database pod of a
namespace on its own node, so the clusters in one namespace need as many nodes
as they have instances together. Set `persistentVolume.storageClass` when the flavor's
default is not suitable. PostgreSQL parameters go in `postgresqlConf`, and any other
`SGCluster` field in `extraSpec`.

Apps should not read the superuser Secret. Give each app a
`packages.experimental.stackgres-database` instance, which creates a role and a
database on the cluster and puts the credentials in the app's namespace. Its
`out` follows the Postgres database contract, `kix.contracts.postgresDatabase`,
which the packages that take a `database` dependency check at evaluation. The
role's password is a secret dependency named `password`, such as a
`packages.secret` instance with a SOPS `source` and `keys = [ "password" ]`.
A secret that Kix does not fill from a SOPS file, such as a `secret-ref` or
an `external-secret`, is also the Secret the app reads. It must hold
`username`, equal to the database's `user`, as well as `password`, with
`keys = [ "username" "password" ]`.

## Back up to object storage

Backups go to an `SGObjectStorage` in the cluster's namespace. Reference the
Secret that holds the storage credentials, add a `stackgres-object-storage`
instance, and turn on `backups`:

```nix
instances.database = {
  backup-credentials = {
    package = packages.secret-ref;
    aliases = [ "storageCredentials" ];
    config.keys = [ "accessKeyId" "secretAccessKey" ];
  };

  backups = {
    package = packages.experimental.stackgres-object-storage;
    config = {
      type = "s3Compatible";
      bucket = "pg-backups";
      extraSpec.s3Compatible = {
        endpoint = "https://s3.example.com";
        region = "example-1";
        enablePathStyleAddressing = true;
      };
    };
  };

  postgres.config.backups = [
    {
      cronSchedule = "0 1 * * *";
      retention = 7;
    }
  ];
};
```

Kix refuses `backups` when no `stackgres-object-storage` instance is in the
same namespace, or when `backups` has more than one entry (StackGres runs only
the first entry). It also refuses a credentials Secret that does not declare
the keys the storage type reads. `credentialKeys` maps those keys to other
names. With backups on, the package sets `archive_timeout` to 60 seconds, so a
quiet database still archives its write-ahead log every minute.

The network policy treats an `endpoint` written in `extraSpec` as an address
outside the cluster. For an S3 store that runs in the cluster, wire the
instance whose root is its S3 Service instead, and leave `endpoint` unset:

```nix
backups.deps.endpointService = ref.minio.minio;
```

The package then sets the endpoint to that Service's URL and turns on
path-style addressing, and the PostgreSQL pods get network policy to the store.

### Back up with a cloud identity

On AWS S3 or Google Cloud Storage, the database pods can authenticate with a
cloud identity instead of a credentials Secret. Configure both the backup
storage and the database cluster:

- On `stackgres-object-storage`, enable pod credentials in `extraSpec`
  (`s3.awsCredentials.useIAMRole = true` for `s3`, or
  `gcs.gcpCredentials.fetchCredentialsFromMetadataService = true` for `gcs`)
  and omit `deps.storageCredentials` (and any `storageCredentials` Secret alias
  in that namespace).
- On each `stackgres-cluster` instance that backs up to that store, pass the
  cloud identity in `deps.backupIdentity`. Because the database pods run
  backups under the `<cluster>-patroni` ServiceAccount created by the StackGres
  operator, each cluster carries its own identity. Leave `deps.backupIdentity`
  unset if the pods should use the cluster's default pod credentials (such as
  the node's credentials on EKS when pods can reach the instance metadata
  service).

```nix
instances.database = {
  backups = {
    package = packages.experimental.stackgres-object-storage;
    config = {
      type = "s3";
      bucket = "pg-backups";
      extraSpec.s3 = {
        region = "eu-west-1";
        awsCredentials.useIAMRole = true;
      };
    };
  };

  postgres = {
    package = packages.experimental.stackgres-cluster;
    deps.backupIdentity = kix.cloudIdentity.aws {
      roleArn = "arn:aws:iam::111122223333:role/postgres-backup";
    };
    config.backups = [ { cronSchedule = "0 1 * * *"; } ];
  };
};
```

Your cluster must include a
[cloud identity provider](/docs/reference/instances-and-composition/#cloud-identities),
such as `kix.flavors.eks` or `kix.flavors.gke`. Kix writes the identity to
`spec.metadata.annotations.serviceAccount` on the `SGCluster`, and the
StackGres operator copies it to the `postgres-patroni` ServiceAccount. Kix does
not create cloud IAM roles or bindings. Configure your AWS IAM role or Google
Cloud IAM binding to trust `system:serviceaccount:database:postgres-patroni`.
Multiple clusters in the same namespace can share one
`stackgres-object-storage` instance and use separate IAM roles, each restricted
to its own backup path.

Evaluation fails when:

- `stackgres-object-storage` sets both `storageCredentials` and a
  pod-credential field (`useIAMRole` or `fetchCredentialsFromMetadataService`),
  or sets neither;
- `useIAMRole` or `fetchCredentialsFromMetadataService` is set on an
  unsupported storage `type` (`useIAMRole` is only for `s3`,
  `fetchCredentialsFromMetadataService` is only for `gcs`, and StackGres
  supports neither on `s3Compatible` or `azureBlob`);
- `credentialKeys` is set when pod credentials are enabled, or a cloud identity
  is passed to `deps.storageCredentials`; or
- `deps.backupIdentity` is set when `backups` is `null`, when
  `stackgres-object-storage` reads a Secret, or when the identity's cloud does
  not match the storage type.

Because the StackGres operator creates the database pods, Kix cannot replace
them automatically when `deps.backupIdentity` changes. The cloud platform
injects credentials only when a pod is created, so running pods keep their old
identity until they are recreated.

After deploying a change to `deps.backupIdentity`, delete each database pod so
StackGres creates a new pod with the updated identity. Do not use an `SGDbOps`
`restart` (`ReducedImpact` or `InPlace`): it completes without recreating the
pod, so the pod keeps its old role.

<Command commands={["kubectl delete pod --namespace <namespace> <cluster>-0"]} />

Delete one pod at a time and wait for its replacement to become ready before
deleting the next. On a multi-instance cluster, delete replicas first and the
primary last so the cluster fails over only once. A single-instance cluster is
unavailable while its pod is recreated.

## Monitor PostgreSQL

When the cluster has a Prometheus provider, such as `prometheus-operator`, the
package adds a `PodMonitor` for the exporter sidecar StackGres runs beside
PostgreSQL. Set `metrics.interval` to change the scrape interval, or
`metrics.enabled = false` to leave the `PodMonitor` out.

## Check the generated resources

Evaluate the cluster before deploying it:

<Command {...check} />

Inspect the custom resources that configure PostgreSQL:

<Command {...databaseResources} />

The `SGCluster` refers to the generated instance profile and PostgreSQL
configuration by name. StackGres uses those resources to create and operate
the StatefulSet, Services, and persistent volume claims.

## Deploy and connect

Deploy the operator and database, then check their status:

<Command
  commands={[
    "kix deploy how-to-package-stackgres",
    "kix status how-to-package-stackgres",
    "kubectl get sgcluster -n database postgres",
  ]}
  cwd="kix-examples/"
/>

The StackGres operator creates a Service and a Secret named `postgres` in the
database namespace. Forward the primary Service port:

<Command commands={["kubectl port-forward -n database service/postgres 5432:5432"]} />

In another terminal, read the generated superuser password and connect:

<Command
  commands={[
    "export PGPASSWORD=$(kubectl get secret -n database postgres -o jsonpath='{.data.superuser-password}' | base64 --decode)",
    "psql --host 127.0.0.1 --username postgres --dbname postgres",
  ]}
/>

Stop the port-forward with `Ctrl-C`. Clear the shell variable when you finish:

<Command commands={["unset PGPASSWORD"]} />

If the `SGCluster` does not become ready, inspect it with `kubectl describe`,
then check the StackGres operator logs and PVC state in the database namespace.