Persist data for MySQL pod using Persistent Volume through cluster restarts

1.2k Views Asked by At

I am trying to deploy a MySQL deployment on Kubernetes and would like to persist data. I am currently able to persist data through the lifetime of the pod (kubectl delete and then kubectl create). However, I am unable to persist data through cluster restarts. Any idea why this is the case?

persistent-volume.yml

apiVersion: v1
kind: PersistentVolume
metadata:
 name: mysql-pv-volume
spec:
 storageClassName: hostpath
 persistentVolumeReclaimPolicy: Retain
 capacity:
  storage: 100Mi
 accessModes:
  - ReadWriteOnce
 hostPath:
  path: "/mnt/data"

persistent-volume-claim.yml

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
 name: mysql-pv-claim
spec:
 storageClassName: hostpath
 accessModes:
  - ReadWriteOnce
 resources:
  requests:
   storage: 100Mi

mysql-deployment.yml

kind: StatefulSet
metadata:
  name: powerplus-db
spec:
  serviceName: powerplus-db
  selector:
    matchLabels:
      app: powerplus-db
  template:
    metadata:
      labels:
        app: powerplus-db
    spec:
      containers:
        - name: powerplus-db
          image: mysql:8.0.21
          env:
            - name: MYSQL_ROOT_PASSWORD
              value: password
            - name: MYSQL_DATABASE
              value: powerplus
          ports:
            - containerPort: 3306
              name: powerplus-db
          volumeMounts:
            - mountPath: /var/lib/mysql
              name: mysql-persistent-storage
      volumes:
        - name: mysql-persistent-storage
          persistentVolumeClaim:
            claimName: mysql-pv-claim```
1

There are 1 best solutions below

0
On

This case is well described in this official guide, especially in paragraph regarding Create PersistentVolumeClaims and PersistentVolumes:

Warning: In local clusters, the default StorageClass uses the hostPath provisioner. hostPath volumes are only suitable for development and testing. With hostPath volumes, your data lives in /tmp on the node the Pod is scheduled onto and does not move between nodes. If a Pod dies and gets scheduled to another node in the cluster, or the node is rebooted, the data is lost.

HostPath is being used for single node testing purposes only. You way want to use a different type of PersisstentVolume. You can find more details regarding the PersistentVolumes types here.