Управляемый сервис MariaDB

Управляемый сервис MariaDB предоставляет мощное и широко используемое решение для работы с реляционными базами данных. Сервис позволяет без лишних сложностей создавать кластер MariaDB с репликацией и управлять им.

Сведения о развертывании

За работу управляемого сервиса отвечает mariadb-operator, который обеспечивает эффективное управление и бесперебойную эксплуатацию.

Параметр storageClass помечен в схеме чарта как неизменяемый. Описание контракта и список компонентов, обеспечивающих его соблюдение, приведены в docs/storage-immutability.md.

Инструкции

Переключение экземпляра primary

kubectl edit mariadb <instance>

Измените:

spec:
  replication:
    primary:
      podIndex: 1

Проверьте состояние:

NAME        READY   STATUS    PRIMARY POD   AGE
<instance>  True    Running   app-db1-1     41d

Резервное копирование и восстановление приложения MariaDB

Рекомендуется использовать сценарий Cozystack на основе BackupClass / Plan / RestoreJob со стратегией strategy.backups.cozystack.io/MariaDB, использующей штатный механизм оператора. Нумерованное пошаговое руководство по всему процессу приведено в examples/backups/mariadb. В нем рассмотрены бакет, источник, стратегия, BackupClass, Plan, разовый BackupJob, а также манифесты RestoreJob для восстановления на месте и восстановления в копию.

Блок чарта backup.* (mariadb-dump + Restic CronJob) объявлен устаревшим и поддерживается только для обратной совместимости. Существующие tenants могут продолжать использовать его без изменений. Для новых развертываний следует использовать описанный выше сценарий на основе штатного механизма оператора.

Восстановление резервной копии, созданной устаревшим механизмом на основе Restic

Найдите снимок:

restic -r s3:s3.example.org/mariadb-backups/database_name snapshots

Выполните восстановление:

restic -r s3:s3.example.org/mariadb-backups/database_name restore latest --target /tmp/

Подробнее:

How to connect over TLS

Kubernetes objects for an instance are named after the Helm release, which prefixes the instance name: an instance mydb produces the Service and Secrets mariadb-mydb-*. The names below use mariadb-<name> for that reason, while <instance> elsewhere in this document is the name of the MariaDB resource itself.

TLS is always served. tls.issuer selects who issues the certificate:

tls.issuerissued bycovers
operator (default)mariadb-operator’s own CAmariadb-<name>, -primary, -secondary, the headless service, localhost
cert-managera CA issued for this instancethe same, plus the external hostname when external is true

The operator has no way to learn the external hostname, so verifying a connection from outside the cluster requires tls.issuer: cert-manager.

The default is operator, and it is not derived from external: switching issuer re-issues the server certificate under a new authority, which breaks any client that pinned the previous ca.crt without making anything safer — those instances already serve TLS.

The field is named for the issuer, not for on/off, because TLS is on either way. Some other charts here spell a similar-looking tls.enabled that does switch TLS on and off; this one deliberately does not, and the enum keeps it from reading as a switch. Epic #2811 tracks converging the TLS surface across charts.

Enforcement is separate. tls.required: true sets require_secure_transport=ON and refuses plaintext, under either issuer. It defaults to false because turning it on disconnects every client not yet using TLS — a decision to make once clients have the CA, not something an upgrade does.

tls.required will default to true in a later release, as an announced change.

Connect with the MariaDB client by supplying the CA and asking for full verification:

mysql -h mariadb-<name> -u <user> -p --ssl-ca=/path/to/ca.crt --ssl-verify-server-cert

-p without a value prompts for the password, which keeps it out of shell history and out of the process arguments other users can read.

--ssl-ca supplies the trust anchor; --ssl-verify-server-cert is what checks the server name against the certificate. Whether that second flag defaults to on depends on the version of the client you connect with, not the server version selected by version: it is off through 10.11 and on from 11.4. Do not read that as “an 11.4 client already verifies”. Without --ssl-ca it has no trust anchor to verify against, and falls back to an anti-tampering check derived from the password hash, which establishes neither the chain nor the hostname — and cannot be derived at all for a passwordless user. --ssl-ca is the load-bearing flag here; pass both and the connection is verified on either client. Note these are MariaDB client options — the MySQL 8 client spells the same intent as --ssl-mode=VERIFY_IDENTITY, which the MariaDB client rejects outright.

The trust anchor is published to tenants as mariadb-<name>.tenant-ca, an object holding ca.crt and nothing else, delivered through the core.cozystack.io/tenantsecrets API that the base tenant roles already grant. It is lifted from the operator’s own key-free mariadb-<name>-ca-bundle, which is reconciled whenever TLS is enabled and follows CA rollovers, but that Secret is not itself granted to tenants: a direct grant on the name would convey whatever happens to occupy it, where the projection conveys only what the platform has vouched for.

kubectl get tenantsecret mariadb-<name>.tenant-ca -o jsonpath='{.data.ca\.crt}' | base64 -d > ca.crt

Verifying an external connection requires tls.issuer: cert-manager. The operator’s certificate does not carry the external hostname, so a client connecting from outside with --ssl-verify-server-cert fails hostname verification against an unmanaged instance no matter which CA it trusts. A cert-manager-issued certificate is what puts mariadb-<name>.<host> in the certificate.

Such clients also need a DNS record pointing at the LoadBalancer address: the hostname is a SAN, the address is not, so connecting to the IP directly fails verification either way.

Migrating an existing instance

An existing instance keeps the operator’s CA and its current enforcement whether or not you upgrade; setting tls.issuer: cert-manager is what moves it to a CA issued for it, and that is the step to plan around.

The deprecated backup.* CronJob also changes: its client now verifies the server it connects to, against mariadb-<name>-ca-bundle, where before it connected without checking. That bundle is present on every instance and carries whichever CA is in use — the operator’s, and the chart’s as well under issuer: cert-manager — and the certificate covers the hostname the job dials, so the verification itself needs no action. Note that this job is separately unable to start — it reads the root password from a Secret name the chart does not render — so on current releases the change is to a job that does not run. Use the BackupClass / Plan flow instead.

Switching issuer does not enforce anything by itself — enforcement is a separate opt-in — but it does change who issues the server certificate. A client that re-reads mariadb-<name>.tenant-ca at connect time follows the change automatically, because the operator keeps both the old and the new CA in mariadb-<name>-ca-bundle, which the projection stays in sync with. A client that copied ca.crt out and pinned it will fail chain validation once the new certificate is served, and has to re-read the anchor.

On a fresh instance created with tls.issuer: cert-manager, the pods do not start until cert-manager has issued the certificates: the operator needs the server certificate before it creates the StatefulSet. This resolves on its own within a reconcile or two — the chart labels the Secrets so the operator is woken as soon as they appear — but the instance looks stalled in the meantime.

The order to change it in:

  1. Switch the issuer and leave enforcement off (the default):

    tls:
      issuer: cert-manager
    

    This step rolls the StatefulSet. The CR gains serverCertSecretRef and serverCASecretRef, which changes the name of the Secret projected into the pods, and a pod-template change restarts them. On a multi-replica instance that is a rolling restart; on a single-replica one it is downtime for as long as one pod takes to come back. Wait for kubectl rollout status statefulset/mariadb-<name> before going on.

  2. Distribute mariadb-<name>.tenant-ca and move clients onto verified TLS one at a time.

  3. Once no plaintext clients remain, require it:

    tls:
      issuer: cert-manager
      required: true
    

Step 3 is the only one that refuses a client by policy, and it happens when you choose it rather than when a platform upgrade rolls through. Step 1 interrupts connections as well, but by restarting the server rather than by rejecting anyone: a client that reconnects is served.

Going back is the same change in reverse: setting tls.issuer: operator hands issuance back, and clients have to pick up the operator’s CA from the bundle again.

One thing does not clean itself up. The Certificates are removed, but cert-manager is configured not to own the Secrets it issued, so mariadb-<name>.ca-tls (the CA private key) and mariadb-<name>.tls (the server private key) stay in the namespace. No tenant grant exposes them, but they are private keys, so remove them.

Wait for the rollout first. mariadb-<name>.tls is mounted into the running pods for as long as the instance still serves the chart-issued certificate, so deleting it before the operator has reissued and rolled the StatefulSet leaves the next pod unable to start:

kubectl rollout status statefulset/mariadb-<name>
kubectl delete secret mariadb-<name>.ca-tls mariadb-<name>.tls --ignore-not-found

Uninstalling the instance does this for you; only the turn-it-off-and-keep-running case needs the manual step.

Известные проблемы

  • Репликация не завершается из-за различных ошибок

  • Репликация не завершается, если журнал binlog очищен

    Пока mariadb-operator не использует mariadbbackup для начальной загрузки узла (эта возможность еще не реализована), выполните следующие действия вручную, чтобы устранить проблему: https://github.com/mariadb-operator/mariadb-operator/issues/141#issuecomment-1804760231

  • Поврежденные индексы Иногда индексы на экземпляре primary могут быть повреждены. Их можно восстановить с экземпляра replica:

    mysqldump -h <slave> -P 3306 -u<user> -p<password> --column-statistics=0 <database> <table> ~/tmp/fix-table.sql
    mysql -h <master> -P 3306 -u<user> -p<password> <database> < ~/tmp/fix-table.sql
    

    When TLS is enforced (tls.required) the server refuses plaintext connections, so add --ssl-ca=/path/to/ca.crt --ssl-verify-server-cert to both commands.

Параметры

Общие параметры

ИмяОписаниеТипЗначение
replicasNumber of MariaDB replicas.int2
resourcesExplicit CPU and memory configuration for each MariaDB replica. When omitted, the preset defined in resourcesPreset is applied.object{}
resources.cpuCPU available to each replica.quantity""
resources.memoryMemory (RAM) available to each replica.quantity""
resourcesPresetDefault sizing preset used when resources is omitted.stringt1.nano
sizePersistent Volume Claim size available for application data.quantity10Gi
storageClassStorageClass used to store the data.string""
externalEnable external access from outside the cluster.boolfalse

TLS parameters

NameDescriptionTypeValue
tlsTLS configuration. Selects who issues the certificates and whether plaintext is refused; TLS itself is always served.object{}
tls.issuerWho issues the server certificate: operator uses the CA mariadb-operator manages itself, cert-manager gives the instance its own CA and is what covers the external hostname. Named for the issuer because TLS is served under both, unlike the similarly-spelled tls.enabled in some other charts, which does switch TLS on and off.stringoperator
tls.requiredRefuse plaintext connections (sets MariaDB require_secure_transport=ON). Applies under either issuer. Opt-in: turn it on once every client connects over TLS, since it disconnects those that do not.*boolnull

Version parameters

NameDescriptionTypeValue
versionMariaDB major.minor version to deploystringv11.8

Параметры приложения

NameDescriptionTypeValue
usersUsers configuration map. Passwords (including the root account) are always auto-generated and stored in the <release>-credentials Secret; they cannot be set from values — read a user’s password from that Secret. A password left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret.map[string]object{}
users[name].maxUserConnectionsMaximum number of connections.int0
databasesDatabases configuration map.map[string]object{}
databases[name].rolesRoles assigned to users.object{}
databases[name].roles.adminList of users with admin privileges.[]string[]
databases[name].roles.readonlyList of users with read-only privileges.[]string[]

Параметры резервного копирования (УСТАРЕЛО)

ИмяОписаниеТипЗначение
backupУСТАРЕЛО: Конфигурация резервного копирования. Рекомендуется использовать сценарий на основе BackupClass / Plan из examples/backups/mariadb/.object{}
backup.enabledУСТАРЕЛО: Включение регулярного резервного копирования (по умолчанию: false).boolfalse
backup.s3RegionУСТАРЕЛО: Регион AWS S3, в котором хранятся резервные копии.stringus-east-1
backup.s3BucketУСТАРЕЛО: Бакет S3 для хранения резервных копий.strings3.example.org/mariadb-backups
backup.scheduleУСТАРЕЛО: Расписание Cron для автоматического резервного копирования.string0 2 * * *
backup.cleanupStrategyУСТАРЕЛО: Стратегия хранения и удаления старых резервных копий.string--keep-last=3 --keep-daily=3 --keep-within-weekly=1m
backup.s3AccessKeyУСТАРЕЛО: Ключ доступа для аутентификации в S3.string<your-access-key>
backup.s3SecretKeyУСТАРЕЛО: Секретный ключ для аутентификации в S3.string<your-secret-key>
backup.resticPasswordУСТАРЕЛО: Пароль для шифрования резервных копий Restic.string<password>

Примеры параметров и справочник

resources и resourcesPreset

resources sets explicit CPU and memory configurations for each replica. Every resource it leaves unset is taken from the preset defined in resourcesPreset.

resources:
  cpu: 4000m
  memory: 4Gi

resourcesPreset задает именованную конфигурацию ресурсов CPU и памяти для каждой реплики. Этот параметр игнорируется, если задано соответствующее значение resources.

Presets follow a cloud-style <series>.<size> naming convention. Five series cover the full CPU-to-memory ratio range (t1 1:0.5, c1 1:1, s1 1:2, u1 1:4, m1 1:8) and each series ships eight sizes (nano through 4xlarge). The legacy flat names (nano, micro, small, medium, large, xlarge, 2xlarge) remain accepted as deprecated aliases and keep their original sizes, which do not follow one series: nano through small equal the t1 sizes of the same name, while medium equals c1.small rather than c1.medium.

Полная матрица размеров и сопоставление прежних имен с типами экземпляров приведены в docs/operations/resource-presets.md.

users

users:
  user1:
    maxUserConnections: 1000
  user2:
    maxUserConnections: 1000

Passwords cannot be set here — they (and the root account) are auto-generated and stored in the <release>-credentials Secret. Read a user’s password with kubectl get secret <release>-credentials -o json | jq -r '.data["user1"]' | base64 -d (a username may contain a ., which jsonpath would treat as a path step and return nothing).

databases

databases:
  myapp1:
    roles:
      admin:
      - user1
      readonly:
      - user2
Last modified 2026-11-03: translate 1.7 (726310fa)