How-to guide / Package task guides
Deploy StackGres
These docs describe Kix's main branch, which can include changes not yet released. Read the docs for the latest release.
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
Section titled “Add the StackGres operator”Install one operator instance in its own namespace:
17 instances.stackgres-system.stackgres-operator = {18 package = packages.experimental.stackgres-operator;19 };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
Section titled “Add the PostgreSQL cluster”Add the database instance in the namespace where it should run:
23 instances.database.postgres = {24 package = packages.experimental.stackgres-cluster;25 config = {26 instances = 1;27 postgres.version = "17";28 persistentVolume.size = "5Gi";29 instanceProfile = {30 cpu = "500m";31 memory = "1Gi";32 };33 };34 };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
Section titled “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:
1instances.database = {2 backup-credentials = {3 package = packages.secret-ref;4 aliases = [ "storageCredentials" ];5 config.keys = [ "accessKeyId" "secretAccessKey" ];6 };7
8 backups = {9 package = packages.experimental.stackgres-object-storage;10 config = {11 type = "s3Compatible";12 bucket = "pg-backups";13 extraSpec.s3Compatible = {14 endpoint = "https://s3.example.com";15 region = "example-1";16 enablePathStyleAddressing = true;17 };18 };19 };20
21 postgres.config.backups = [22 {23 cronSchedule = "0 1 * * *";24 retention = 7;25 }26 ];27};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:
1backups.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
Section titled “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 inextraSpec(s3.awsCredentials.useIAMRole = truefors3, orgcs.gcpCredentials.fetchCredentialsFromMetadataService = trueforgcs) and omitdeps.storageCredentials(and anystorageCredentialsSecret alias in that namespace). - On each
stackgres-clusterinstance that backs up to that store, pass the cloud identity indeps.backupIdentity. Because the database pods run backups under the<cluster>-patroniServiceAccount created by the StackGres operator, each cluster carries its own identity. Leavedeps.backupIdentityunset 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).
1instances.database = {2 backups = {3 package = packages.experimental.stackgres-object-storage;4 config = {5 type = "s3";6 bucket = "pg-backups";7 extraSpec.s3 = {8 region = "eu-west-1";9 awsCredentials.useIAMRole = true;10 };11 };12 };13
14 postgres = {15 package = packages.experimental.stackgres-cluster;16 deps.backupIdentity = kix.cloudIdentity.aws {17 roleArn = "arn:aws:iam::111122223333:role/postgres-backup";18 };19 config.backups = [ { cronSchedule = "0 1 * * *"; } ];20 };21};Your cluster must include a
cloud identity provider,
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-storagesets bothstorageCredentialsand a pod-credential field (useIAMRoleorfetchCredentialsFromMetadataService), or sets neither;useIAMRoleorfetchCredentialsFromMetadataServiceis set on an unsupported storagetype(useIAMRoleis only fors3,fetchCredentialsFromMetadataServiceis only forgcs, and StackGres supports neither ons3CompatibleorazureBlob);credentialKeysis set when pod credentials are enabled, or a cloud identity is passed todeps.storageCredentials; ordeps.backupIdentityis set whenbackupsisnull, whenstackgres-object-storagereads 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.
❱ 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
Section titled “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
Section titled “Check the generated resources”Evaluate the cluster before deploying it:
❱ kix check how-to-package-stackgres
TOOL RESULT DETAILS
eval pass 39 manifests evaluated
scorecard pass 0 errors, 1 warnings, 0 info
security.hasNetworkPolicy (warning), 1:
stackgres-system: namespace 'stackgres-system' has workloads but no network policy Inspect the custom resources that configure PostgreSQL:
❱ kix build how-to-package-stackgres --output json
[
{
"apiVersion": "stackgres.io/v1",
"kind": "SGCluster",
"metadata": {
"name": "postgres",
"namespace": "database"
},
"spec": {
"instances": 1,
"postgres": {
"version": "17"
},
"sgInstanceProfile": "postgres-profile",
"configurations": {
"sgPostgresConfig": "postgres-pg17-config"
},
"persistentVolume": {
"size": "5Gi",
"storageClass": "standard"
}
}
},
{
"apiVersion": "stackgres.io/v1",
"kind": "SGInstanceProfile",
"metadata": {
"name": "postgres-profile",
"namespace": "database"
},
"spec": {
"cpu": "500m",
"memory": "1Gi"
}
}
] 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
Section titled “Deploy and connect”Deploy the operator and database, then check their status:
❱ kix deploy how-to-package-stackgres❱ kix status how-to-package-stackgres❱ kubectl get sgcluster -n database postgres The StackGres operator creates a Service and a Secret named postgres in the
database namespace. Forward the primary Service port:
❱ kubectl port-forward -n database service/postgres 5432:5432 In another terminal, read the generated superuser password and connect:
❱ 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:
❱ 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.