k8s MySQL – HostPath

Precondition

namespace: db

kubectl create namespace db

Create secret with password 1234

kubectl create secret generic mysql-password -n db \
      --from-literal=password=1234
  • StorageClass
  • PersistentVolume
  • PersistentVolumeClaim
  • Deployment
    • MySQL 5.7, Replicaset 3
  • Service
---
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: local-storage
allowVolumeExpansion: true
provisioner: kubernetes.io/no-provisioner

---
apiVersion: v1
kind: PersistentVolume
metadata:
  name: mysql-pv
  labels:
    type: local
spec:
  storageClassName: local-storage
  capacity:
    storage: 100Mi
  accessModes:
    - ReadWriteOnce
  hostPath:
    # Minikube will only persist host paths located under /data, not anything located under
    path: "/data"
    type: DirectoryOrCreate

---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mysql-pvc
  namespace: db
spec:
  storageClassName: local-storage
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 100Mi

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mysql-deployment
  namespace: db
  labels:
    app: mysql
spec:
  replicas: 3
  selector:
    matchLabels:
      app: mysql
  strategy:
    type: Recreate
  template:
    metadata:
      name: mysql-pod
      namespace: db
      labels:
        app: mysql
    spec:
      containers:
        - image: mysql:5.7
          name: mysql
          env:
            - name: MYSQL_ROOT_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: mysql-password
                  key: password
          ports:
            - containerPort: 3306
              protocol: TCP
              name: mysql
          volumeMounts:
            - name: mysql-persistent-storage
              mountPath: /var/lib/mysql
      volumes:
        - name: mysql-persistent-storage
          persistentVolumeClaim:
            claimName: mysql-pvc

---
apiVersion: v1
kind: Service
metadata:
  name: mysql-service
  namespace: db
  labels:
    app: mysql
spec:
  selector:
    app: mysql
  type: NodePort
  ports:
    - targetPort: 3306
      port: 3306
      nodePort: 30002

Leave a Reply

Your email address will not be published.

ANOTE.DEV