How-to guide / Package task guides
Create databases with DB Operator
These docs describe Kix's main branch, which can include changes not yet released. Read the docs for the latest release.
Use packages.experimental.db-operator,
packages.experimental.db-operator-instance, and
packages.experimental.db-operator-database to create a PostgreSQL database,
login role, and credentials Secret for each application with
DB Operator 2.47.0.
Your cluster needs packages.experimental.cert-manager (see
Configure cert-manager issuers)
and a PostgreSQL server, either in the cluster (cnpg-cluster or
stackgres-cluster) or outside it. You also need a PostgreSQL admin account
that can create roles, databases, and any extensions your applications request.
Add DB Operator
Section titled “Add DB Operator”Install one db-operator instance in its own namespace:
152 instances.db-operator.db-operator = {153 package = packages.experimental.db-operator;154 config = {155 metrics.enabled = true;156 settings.serverVersionTTL = "30m";157 env.DBO_RECONCILE_INTERVAL = "30s";158 webhook.env.DBO_LOG_LEVEL = "info";159 };160 };Declare only one db-operator instance per cluster; it manages databases across
all namespaces. It deploys the controller and admission webhook, uses
cert-manager (found automatically, or set with deps.certManager) to issue a
self-signed webhook certificate, and waits for the webhook to respond before Kix
applies any DbInstance, Database, or DbUser resources.
All config fields shown above are optional:
metrics.enabled(defaulttrue): creates aServiceMonitorand three Prometheus alert rules (DbOperatorDown,DbOperatorReconcileErrors, andDbOperatorDatabaseFailing) when the cluster includes a Prometheus provider such asprometheus-operator.DbOperatorDatabaseFailingfires when aDatabasethat was ready in the last 6 hours has been unready for 15 minutes.resources: CPU and memory requests and limits for the controller (default memory limit512Mi; setwebhook.resourcesfor the webhook server). Because the controller caches everySecretandConfigMapin the cluster, raiseresources.limits.memoryon clusters with many or large Secrets and ConfigMaps, or if the controller is OOM-killed. In testing, controller memory grew from about 48 MiB idle to about 185 MB with 10,000 Secrets of 8 KiB each.settings: merged into the controller’sconfig.yamlover the defaultsdatabaseAwareness = trueandserverVersionTTL = "1h". Changingsettingsrestarts the controller pods.envandwebhook.env: pass extraDBO_*environment variables to the controller and webhook server. Kix rejects variables that the package sets or reserves:DBO_CONFIG,DBO_WATCH_NAMESPACES,DBO_ENABLE_LEADER_ELECTION,DBO_METRICS_ADDR, andDBO_PROBE_ADDR.
Register a PostgreSQL server
Section titled “Register a PostgreSQL server”Add a db-operator-instance in the namespace that holds the server’s admin
Secret. Here, ref.data.pg is a packages.cnpg-cluster instance in the
data namespace with extraSpec.enableSuperuserAccess = true, which tells
CloudNativePG to write a pg-superuser Secret:
174 pg-superuser = {175 package = packages.secret-ref;176 config = {177 type = "kubernetes.io/basic-auth";178 keys = [179 "username"180 "password"181 ];182 };183 };184 pg-instance = {185 package = packages.experimental.db-operator-instance;186 deps = {187 postgres = ref.data.pg;188 adminCredentials = ref.data.pg-superuser;189 };190 # A Go regular expression, matched anywhere in the namespace name.191 config.extraSpec.namespaceFilters = [ "^apps$" ];192 };db-operator-instance finds dbOperator automatically and takes two explicit
dependencies:
postgres: the PostgreSQL server. Pass any instance that publishesout.fqdnandout.port, such ascnpg-cluster,stackgres-cluster(see Deploy StackGres),service-ref, orkix.mkImport.adminCredentials: a secret in the same namespace holding the admin username and password. Here,pg-superuserusespackages.secret-refto point to CloudNativePG’spg-superuserSecret(secret-refuses the instance name as theSecretname by default). By default,db-operator-instancereads theusernameandpasswordkeys. If yourSecretuses different keys (such as"superuser-username"and"superuser-password"for StackGres), setauth.usernameKeyandauth.passwordKey. The account (such as thepostgressuperuser) must have permission to create roles, databases, and any requested extensions.
Give each db-operator-instance a unique name across the whole cluster, because
the DbInstance resource it creates is cluster-scoped.
By default, any namespace can create databases on the server. In the snippet
above, extraSpec.namespaceFilters = [ "^apps$" ] limits the server to the
apps namespace. Each filter is a Go regular expression matched anywhere in the
namespace name, so "apps" also matches myapps and apps-staging. Anchor
exact names with ^ and $. If you create a Database in an excluded
namespace, it never becomes ready and kix deploy eventually times out.
When deps.postgres publishes out.tls = true (as cnpg-cluster does),
db-operator-instance enables TLS with skip-verify = true. DB Operator 2.47
cannot load custom CA certificates for database servers, so it can only verify
certificates signed by a public CA. If your server uses a public CA certificate,
set extraSpec.endpoint.sslConnection.skip-verify = false.
Use a server outside the cluster
Section titled “Use a server outside the cluster”To register a PostgreSQL server outside the cluster, declare it with
kix.mkImport and set external = true:
1instances.data.pg.package = kix.mkImport {2 out = {3 fqdn = "db.example.com";4 port = "5432";5 tls = true;6 external = true;7 };8};When network policies are enabled, external = true lets DB Operator’s
controller pods reach any external IP address on that TCP port (Kubernetes
network policies cannot filter by external DNS name). Without external = true,
default-deny network policies block the operator from reaching the server and
the DbInstance never becomes ready. Kix does not add egress rules from your
application pods to an external database server; if your cluster enforces
default-deny egress, add egress rules for those applications yourself.
Create an application database
Section titled “Create an application database”In the application’s namespace (here apps), add a db-operator-database
instance and point deps.dbInstance at your server (dbOperator is found
automatically):
198 app-db = {199 package = packages.experimental.db-operator-database;200 deps.dbInstance = ref.data.pg-instance;201 config = {202 extensions = [ "citext" ];203 templates.DATABASE_URL = "postgresql://{{ .Username }}:{{ .Password }}@{{ .Hostname }}:{{ .Port }}/{{ .Database }}";204 extraSpec.postgres.schemas = [ "app" ];205 };206 };DB Operator connects with the admin account (postgres here) to create a
PostgreSQL database and login role both named <namespace>-<instance>
(apps-app-db here). The admin account owns the database, while the new role
gets all privileges on the database, public, and each schema in
extraSpec.postgres.schemas, so the application can create tables without
owning the database or schemas. DB Operator generates a password for the role
and writes a Secret and ConfigMap named <instance>-credentials
(app-db-credentials) in the application’s namespace. The Secret contains
POSTGRES_DB, POSTGRES_USER, POSTGRES_PASSWORD, username, password, and
one key for each entry in templates.
Keep <namespace>-<instance> to 63 bytes or fewer; Kix rejects longer names
because PostgreSQL truncates identifiers past 63 bytes.
Also make sure <namespace>-<instance> is unique on each DbInstance, because
kix check cannot detect hyphen collisions. For example, instance c in
namespace a-b and instance b-c in namespace a both produce a-b-c. On the
same DbInstance, they share one PostgreSQL database and role, so each
application can read the other’s tables. Worse, each Secret holds a different
password: only one application can log in at a time, and the other fails with
"password authentication failed". Which application can log in may change over
time (for example, after a controller restart), while both Database resources
still report ready.
All config fields shown above are optional:
extensions: PostgreSQL extensions to enable in this database at the server’s default version (each extension must already be installed on the server). Kix rejects pinned extension versions.templates: extra keys added to the credentialsSecret, each rendered as a Go template. Templates can use the fields.Username,.Password,.Hostname,.Port,.Database, and.Protocol, and the functions.Secret,.ConfigMap,.Query, and.InstanceVar; Kix rejects any other field duringkix check. DB Operator inserts values without escaping, so special characters in a generated password can break a URL template.extraSpec: additional fields merged into theDatabasespec, such aspostgres.schemas. Kix rejectsinstance,secretName,existingUser,credentials.templates,secretsTemplates, andpostgres.extensionshere because the package manages those settings.
Databases keep their data when removed (extraSpec.deletionProtected defaults
to true). If you remove a db-operator-database instance and deploy with
--prune, Kix deletes the Database resource, while the PostgreSQL database,
login role, and data stay on the server. The <instance>-credentials Secret
(including any templates keys) and ConfigMap also stay in the namespace,
with only DB Operator’s kinda.rocks/used-by-kind and
kinda.rocks/used-by-name labels removed from the Secret. Adding the same
instance back later reuses that Secret and password, so the application
reconnects to its existing data. Set extraSpec.deletionProtected = false if
you want DB Operator to drop the database and role when the Database resource
is deleted.
Connect an application to the database
Section titled “Connect an application to the database”Application packages that take a database dependency, such as metabase,
keycloak, vaultwarden, n8n, and harbor, work with db-operator-database
without changes. Place the db-operator-database instance in the same namespace
as the application (Kubernetes pods can only read Secrets in their own
namespace). Kix connects a single database in the namespace automatically, or
you can wire deps.database = ref.apps.app-db explicitly. Like cnpg-database
and stackgres-database, db-operator-database satisfies
kix.contracts.postgresDatabase and publishes out.host, out.port,
out.database, out.username, out.credentials, out.extensions, and
out.tls.
Two package-specific notes:
harborneeds to know whether PostgreSQL uses TLS, so either use a server that publishesout.tls(trueorfalse, ascnpg-clusterdoes) or setdatabase.sslmodeon theharborinstance.immichrequests a pinned version of thevchordextension, which DB Operator cannot pin. Kix rejectsimmichwithdb-operator-databaseduringkix check; usecnpg-databaseorstackgres-databaseforimmich.
In a custom package, read connection fields from database.out and secret keys
with database.out.credentials.out.keyRef (or database.out.credentials.out.mkEnv):
1env = kix.mkEnvVars {2 PGHOST = database.out.host;3 PGPORT = database.out.port;4 PGDATABASE = database.out.database;5 PGSSLMODE = if database.out.tls or null == true then "require" else "prefer";6 PGUSER = database.out.credentials.out.keyRef "username";7 PGPASSWORD = database.out.credentials.out.keyRef "password";8};During kix check, Kix verifies that workloads read only keys declared on the
credentials Secret. During kix deploy, Kix waits for DB Operator to create
the Secret with all declared keys before starting workloads that read it.
Because DB Operator generates the password inside the cluster, Kix cannot track
changes to the Secret’s contents; restart application pods yourself after
rotating a password.
When network policies are enabled
(networkPolicy.enable = true), Kix generates rules allowing traffic from the
Kubernetes API server to the webhook on TCP 9443, and from the operator
controller and applications that use the database to in-cluster PostgreSQL
servers.
Remove or rename instances
Section titled “Remove or rename instances”-
Removing a server or the operator. First remove the
db-operator-databaseinstances, runkix deploy <cluster> --prune, and wait untilkubectl get database -Alists none (kix statusstops listing aDatabaseonce you remove it from the cluster definition). Only then removedb-operator-instanceordb-operatorand deploy with--pruneagain.Each
Databasehas a finalizer (db.<instance>) that requires both thedb-operatorcontroller and itsDbInstance. Althoughkix deploy --prunedeletes aDatabasebefore itsDbInstance, it does not wait for the finalizer to finish; if theDbInstanceor controller disappears first (for example, while the controller is slow, restarting, or scaled to zero), theDatabasegets stuck inTerminating(loggingDbInstance.kinda.rocks "<name>" not foundwhen theDbInstanceis missing). To recover, add the removeddb-operator-instanceordb-operatorback to the cluster definition, deploy, wait about 50 seconds (the controller’s retry delay) untilkubectl get database -Ais empty, and then remove it again withkix deploy <cluster> --prune. -
Narrowing namespace filters. Remove
db-operator-databaseinstances in namespaces you plan to exclude, runkix deploy <cluster> --prune, and wait until theirDatabaseresources are gone before narrowingextraSpec.namespaceFilters. Because the controller checksnamespaceFiltersbefore handling deletions, doing both in one deploy leaves thoseDatabaseresources stuck inTerminatingwith"namespace <ns> is not allowed on the instance". To recover, widenextraSpec.namespaceFilters, deploy, wait until theDatabaseresources are gone, and then narrow the filters. -
Renaming or switching a server. Do not rename a
db-operator-instancewhiledb-operator-databaseinstances still use it, and do not point an existingdb-operator-databaseat a differentdeps.dbInstance. DB Operator’s admission webhook rejects changes tospec.instanceon an existingDatabase, sokix deployfails. -
Renaming or moving a database. Renaming a
db-operator-databaseinstance or moving it to another namespace creates a new, empty PostgreSQL database and role (<namespace>-<instance>). The old database and role stay on the server. -
Pre-existing
<instance>-credentialsSecrets. Before deploying a newdb-operator-database, make sure noSecretnamed<instance>-credentialsalready exists in the namespace (unless left behind by the same instance). Otherwise, DB Operator adopts thatSecretand reads the database and role names from itsPOSTGRES_DBandPOSTGRES_USERkeys, which may differ from the<namespace>-<instance>name Kix publishes inout.databaseandout.username.
Check and deploy
Section titled “Check and deploy”Check and deploy your cluster:
❱ kix check <cluster>❱ kix deploy <cluster> Verify the DbInstance, the Database, and the credentials Secret:
❱ kubectl get dbinstance pg-instance❱ kubectl get database -n apps app-db❱ kubectl get secret -n apps app-db-credentials Confirm that pg-instance shows true in the READY column, app-db shows
true in the STATUS column, and app-db-credentials exists in apps.
If a DbInstance stays unready, inspect its CredentialsFound,
EndpointFound, and Healthy conditions and check the controller logs:
❱ kubectl describe dbinstance <name>❱ kubectl logs -n db-operator deploy/db-operator-controller If a Database stays false in STATUS, inspect its Events for the error:
❱ kubectl describe database -n <ns> <name>