Helm chartv0.4.0App 8.4.3

MySQL relational database with replication support

About this chart

MySQL Helm Chart

MySQL relational database with replication support for Kubernetes

Features

  • StatefulSet Deployment: Stable pod identities and persistent storage for data durability
  • Master-Replica Replication: Optional MySQL replication for high availability and read scaling
  • Persistent Storage: PersistentVolumeClaim support with configurable storage class and size
  • Configuration Management: Complete my.cnf configuration via ConfigMap
  • Security: Kubernetes secrets for password management, security contexts, and non-root execution
  • Health Probes: Liveness and readiness probes using mysqladmin ping
  • Resource Management: Configurable CPU and memory limits/requests
  • Flexible Deployment: Development and production value profiles included
  • Operational Tools: Comprehensive Makefile commands for database operations

TL;DR

# Add the repository
helm repo add scripton-charts https://scriptonbasestar-container.github.io/sb-helm-charts
helm repo update

# Install with default configuration (single node)
helm install my-mysql scripton-charts/mysql

# Install with custom root password
helm install my-mysql scripton-charts/mysql \
  --set mysql.password=mySecurePassword

# Install with replication (2 replicas)
helm install my-mysql scripton-charts/mysql \
  --set replicaCount=2 \
  --set mysql.replication.enabled=true \
  --set mysql.replication.password=replicatorPassword

Prerequisites

  • Kubernetes 1.19+
  • Helm 3.0+
  • PV provisioner support in the underlying infrastructure (for persistence)

Installing the Chart

Basic Installation

Install the chart with the release name my-mysql:

helm install my-mysql scripton-charts/mysql

Development Installation

Use the development values for local testing:

helm install my-mysql scripton-charts/mysql \
  -f https://raw.githubusercontent.com/scriptonbasestar-container/sb-helm-charts/master/charts/mysql/values-dev.yaml

Production Installation

Use the production values with replication:

helm install my-mysql scripton-charts/mysql \
  -f https://raw.githubusercontent.com/scriptonbasestar-container/sb-helm-charts/master/charts/mysql/values-small-prod.yaml \
  --set mysql.password=mySecurePassword \
  --set mysql.replication.password=replicatorPassword

Uninstalling the Chart

To uninstall/delete the my-mysql deployment:

helm uninstall my-mysql

This command removes all the Kubernetes components associated with the chart and deletes the release.

Note: PersistentVolumeClaims are not automatically deleted. You must delete them manually if needed:

kubectl delete pvc -l app.kubernetes.io/instance=my-mysql

Configuration

The following table lists the configurable parameters of the MySQL chart and their default values.

Global Parameters

ParameterDescriptionDefault
replicaCountNumber of MySQL replicas1
image.repositoryMySQL image repositorymysql
image.pullPolicyImage pull policyIfNotPresent
image.tagMySQL image tag (overrides chart appVersion)""
imagePullSecretsDocker registry secret names[]
nameOverrideOverride chart name""
fullnameOverrideOverride full chart name""

MySQL Configuration

ParameterDescriptionDefault
mysql.databaseDatabase to create on first startupmysql
mysql.usernameUsername to create on first startupmysql
mysql.passwordPassword for the user (auto-generated if empty)""
mysql.maxConnectionsMaximum concurrent connections100
mysql.innodbBufferPoolSizeInnoDB buffer pool size128M
mysql.innodbLogFileSizeInnoDB log file size48M
mysql.replication.enabledEnable MySQL replicationfalse
mysql.replication.userReplication userreplicator
mysql.replication.passwordReplication user password""
mysql.replication.serverIdServer ID for replication1
mysql.configAdditional MySQL configuration{}
mysql.existingConfigMapUse existing ConfigMap for configuration""
mysql.existingSecretUse existing Secret for passwords""
mysql.extraEnvAdditional environment variables[]

Service Configuration

ParameterDescriptionDefault
service.typeKubernetes service typeClusterIP
service.portMySQL service port3306
service.nodePortNodePort (if service type is NodePort)""
service.annotationsService annotations{}

Persistence Configuration

ParameterDescriptionDefault
persistence.enabledEnable persistence using PVCtrue
persistence.storageClassPVC storage class""
persistence.accessModePVC access modeReadWriteOnce
persistence.sizePVC storage size10Gi
persistence.annotationsPVC annotations{}

Security Configuration

ParameterDescriptionDefault
serviceAccount.createCreate service accounttrue
serviceAccount.annotationsService account annotations{}
serviceAccount.nameService account name""
podAnnotationsPod annotations{}
podSecurityContext.fsGroupPod fsGroup999
podSecurityContext.runAsUserPod runAsUser999
podSecurityContext.runAsNonRootRun as non-root usertrue
securityContext.capabilities.dropDropped Linux capabilities[ALL]
securityContext.readOnlyRootFilesystemRead-only root filesystemfalse
securityContext.allowPrivilegeEscalationAllow privilege escalationfalse

Resource Configuration

ParameterDescriptionDefault
resources.limits.cpuCPU limit1000m
resources.limits.memoryMemory limit1Gi
resources.requests.cpuCPU request250m
resources.requests.memoryMemory request512Mi

Health Probe Configuration

ParameterDescriptionDefault
livenessProbe.initialDelaySecondsLiveness probe initial delay30
livenessProbe.periodSecondsLiveness probe period10
livenessProbe.timeoutSecondsLiveness probe timeout5
livenessProbe.failureThresholdLiveness probe failure threshold6
readinessProbe.initialDelaySecondsReadiness probe initial delay10
readinessProbe.periodSecondsReadiness probe period10
readinessProbe.timeoutSecondsReadiness probe timeout5
readinessProbe.failureThresholdReadiness probe failure threshold3

Node Selection

ParameterDescriptionDefault
nodeSelectorNode labels for pod assignment{}
tolerationsTolerations for pod assignment[]
affinityAffinity rules for pod assignment{}

Common Configurations

Single Node Development

# values-dev.yaml
replicaCount: 1
mysql:
  database: "testdb"
  username: "testuser"
  password: "testpass"
  maxConnections: 50
  innodbBufferPoolSize: "64M"
persistence:
  size: 5Gi
resources:
  limits:
    cpu: 500m
    memory: 512Mi
  requests:
    cpu: 100m
    memory: 256Mi

Production with Replication

# values-prod.yaml
replicaCount: 2
mysql:
  database: "production_db"
  username: "app_user"
  password: ""  # Set via --set or external secret
  maxConnections: 200
  innodbBufferPoolSize: "512M"
  innodbLogFileSize: "128M"
  replication:
    enabled: true
    password: ""  # Set via --set or external secret
persistence:
  storageClass: "fast-ssd"
  size: 50Gi
resources:
  limits:
    cpu: 2000m
    memory: 2Gi
  requests:
    cpu: 500m
    memory: 1Gi
affinity:
  podAntiAffinity:
    preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 100
        podAffinityTerm:
          labelSelector:
            matchExpressions:
              - key: app.kubernetes.io/name
                operator: In
                values:
                  - mysql
          topologyKey: kubernetes.io/hostname

Custom Configuration

mysql:
  config:
    max_allowed_packet: "64M"
    innodb_flush_log_at_trx_commit: "1"
    innodb_flush_method: "O_DIRECT"
    query_cache_size: "0"
    query_cache_type: "0"

Replication Setup

MySQL replication provides high availability and read scaling. This chart supports master-replica replication.

Enable Replication

  1. Install with at least 2 replicas:
helm install my-mysql scripton-charts/mysql \
  --set replicaCount=2 \
  --set mysql.replication.enabled=true \
  --set mysql.replication.password=replicatorPassword
  1. The first pod (my-mysql-0) becomes the master
  2. Subsequent pods (my-mysql-1, my-mysql-2, etc.) become replicas

Check Replication Status

# Check all pods
make -f make/ops/mysql.mk mysql-replication-info

# Check master status
make -f make/ops/mysql.mk mysql-master-status POD=my-mysql-0

# Check replica status
make -f make/ops/mysql.mk mysql-replica-status POD=my-mysql-1

# Check replication lag
make -f make/ops/mysql.mk mysql-replica-lag

Replication Architecture

┌─────────────────────┐
│   my-mysql-0        │
│   (Master)          │
│   Read + Write      │
└──────────┬──────────┘
           │ Binary Log
           ├────────────────┐
           │                │
           ▼                ▼
┌──────────────────┐ ┌──────────────────┐
│  my-mysql-1      │ │  my-mysql-2      │
│  (Replica)       │ │  (Replica)       │
│  Read Only       │ │  Read Only       │
└──────────────────┘ └──────────────────┘

Backup and Restore

Manual Backup

Backup all databases:

make -f make/ops/mysql.mk mysql-backup

This creates a compressed SQL dump in tmp/mysql-backups/.

Backup Specific Database

kubectl exec my-mysql-0 -- bash -c \
  "mysqldump -uroot -p\$MYSQL_ROOT_PASSWORD mydb --single-transaction" \
  | gzip > mydb-backup.sql.gz

Restore from Backup

make -f make/ops/mysql.mk mysql-restore FILE=tmp/mysql-backups/mysql-backup-20240101-120000.sql.gz

Automated Backups

For production, consider using external backup solutions:

  • Velero: Kubernetes backup and restore
  • mysqldump CronJob: Scheduled backups to object storage
  • Percona XtraBackup: Hot backups for large databases

Operational Commands

This chart includes comprehensive Makefile commands for database operations.

Basic Operations

# Open MySQL shell
make -f make/ops/mysql.mk mysql-shell

# View logs
make -f make/ops/mysql.mk mysql-logs

# Port forward to localhost:3306
make -f make/ops/mysql.mk mysql-port-forward

Database Management

# Create database
make -f make/ops/mysql.mk mysql-create-db DB=mydb

# List all databases
make -f make/ops/mysql.mk mysql-list-dbs

# Show database sizes
make -f make/ops/mysql.mk mysql-db-size

# Optimize database
make -f make/ops/mysql.mk mysql-optimize DB=mydb

User Management

# Create user
make -f make/ops/mysql.mk mysql-create-user USER=myuser PASSWORD=mypass

# Grant privileges
make -f make/ops/mysql.mk mysql-grant-privileges USER=myuser DB=mydb

# List users
make -f make/ops/mysql.mk mysql-list-users

# Show user grants
make -f make/ops/mysql.mk mysql-show-grants USER=myuser

Performance Monitoring

# Show server status
make -f make/ops/mysql.mk mysql-status

# Show running processes
make -f make/ops/mysql.mk mysql-processlist

# Show server variables
make -f make/ops/mysql.mk mysql-variables

# Show InnoDB status
make -f make/ops/mysql.mk mysql-innodb-status

Maintenance

# Check tables
make -f make/ops/mysql.mk mysql-check DB=mydb

# Repair tables
make -f make/ops/mysql.mk mysql-repair DB=mydb

# Analyze tables
make -f make/ops/mysql.mk mysql-analyze DB=mydb

Custom Commands

# Run MySQL command
make -f make/ops/mysql.mk mysql-cli CMD="SELECT VERSION();"

# Run mysqladmin command
make -f make/ops/mysql.mk mysql-admin CMD=ping

# Check version
make -f make/ops/mysql.mk mysql-version

For a complete list of commands:

make -f make/ops/mysql.mk help

Backup & Recovery Strategy

This chart supports a comprehensive 5-component backup strategy for production-grade data protection.

Backup Components Overview

ComponentRPORTOUse CaseStorage
ConfigurationDaily< 5 minInfrastructure recoveryGit + S3
Logical Dumps24 hours30 min - 2 hrsDatabase restoreS3 Standard
Binary Logs5-15 minutes30 min - 1 hrPoint-in-Time Recovery (PITR)S3 Standard
ReplicationNear-zero< 5 minHigh availabilityLive replica
PVC SnapshotsWeekly30 min - 2 hrsDisaster recoveryCSI Snapshots

Quick Backup Commands

# Full backup (all databases)
make -f make/ops/mysql.mk mysql-backup-all

# Single database backup
make -f make/ops/mysql.mk mysql-backup DATABASE=myapp

# Configuration backup
make -f make/ops/mysql.mk mysql-backup-config

# Binary log archiving
make -f make/ops/mysql.mk mysql-archive-binlogs

# PVC snapshot
make -f make/ops/mysql.mk mysql-backup-pvc-snapshot

# Verify backup
make -f make/ops/mysql.mk mysql-backup-verify FILE=tmp/mysql-backups/backup.sql.gz

Deploy mysql with OpenTenant

Each tenant gets its own release of this chart, with its own namespace, secrets and domain. The builder below already has mysql on a Hetzner server. Change the host, add apps from the marketplace, then copy the generated files. Providers and prices are samples, and nothing here is sent anywhere.

  1. Pick a serverConnect Hetzner, OVHcloud or AWS. The builder starts on Hetzner, the cheapest sample rate.
  2. Place the chartmysql is pinned at v0.4.0 in opentenant.yaml. Drag more apps from the marketplace onto a rack.
  3. ApplySave opentenant.yaml and main.tf from the console, then run the commands below.
# opentenant.yaml, main.tf and dns.tf come from the builder below
opentenant validate opentenant.yaml
terraform init && terraform apply