How do you run MySQL on Kubernetes or Docker Compose for a dev environment?

IntermediateHands-onMySQL
Answer

Short answer

Use the official mysql image, set credentials through environment variables (from a Secret in Kubernetes), and mount a persistent volume at /var/lib/mysql so data survives restarts. For Kubernetes, use a StatefulSet with a PVC; for production, prefer a managed service or an operator.

Docker Compose

services:
  db:
    image: mysql:8.4
    environment:
      MYSQL_ROOT_PASSWORD: rootpass
      MYSQL_DATABASE: shop
      MYSQL_USER: shop_app
      MYSQL_PASSWORD: apppass
    ports: ["3306:3306"]
    volumes:
      - dbdata:/var/lib/mysql
      - ./init:/docker-entrypoint-initdb.d      # *.sql run on first start
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
      interval: 5s
  app:
    build: .
    depends_on: { db: { condition: service_healthy } }
    environment: { DB_HOST: db }
volumes: { dbdata: {} }

Kubernetes (simplified StatefulSet)

apiVersion: apps/v1
kind: StatefulSet
metadata: { name: mysql }
spec:
  serviceName: mysql
  replicas: 1
  selector: { matchLabels: { app: mysql } }
  template:
    metadata: { labels: { app: mysql } }
    spec:
      containers:
        - name: mysql
          image: mysql:8.4
          envFrom: [{ secretRef: { name: mysql-creds } }]
          ports: [{ containerPort: 3306 }]
          volumeMounts: [{ name: data, mountPath: /var/lib/mysql }]
  volumeClaimTemplates:
    - metadata: { name: data }
      spec: { accessModes: [ReadWriteOnce], resources: { requests: { storage: 20Gi } } }

Apps connect to mysql-0.mysql.<namespace>.svc.cluster.local or a Service named mysql.

What to say in the interview

"Official image, credentials via env from a Secret, data on a persistent volume, a health check so the app waits for it. On Kubernetes that's a StatefulSet with volumeClaimTemplates; for production we'd use RDS or an operator like the MySQL Operator for backups and failover."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: MySQL basics

More on MySQL