Part of the power of Kubernetes containers comes from their ephemeral nature. They can be easily created, destroyed, and replaced, and this makes them easy to manage. However, sometimes we need to maintain persistent data that survives beyond the life of a pod. In this lab, we will go through how to implement state persistence using PersistentVolumes and PersistentVolume claims. We will create persistent storage and consume it using a pod.
Learning Objectives
Successfully complete this lab by achieving the following learning objectives:
- Create a PersistentVolume
Create a descriptor file with
vi mysql-pv.yml
:kind: PersistentVolume apiVersion: v1 metadata: name: mysql-pv spec: storageClassName: localdisk capacity: storage: 1Gi accessModes: - ReadWriteOnce hostPath: path: "/mnt/data"
Create the PersistentVolume.
kubectl apply -f mysql-pv.yml
- Create a PersistentVolumeClaim
Create a descriptor file with
vi mysql-pv-claim.yml
:apiVersion: v1 kind: PersistentVolumeClaim metadata: name: mysql-pv-claim spec: storageClassName: localdisk accessModes: - ReadWriteOnce resources: requests: storage: 500Mi
Create the PersistentVolumeClaim:
kubectl apply -f mysql-pv-claim.yml
- Create a MySQL Pod configured to use the PersistentVolumeClaim
Create a descriptor file with
vi mysql-pod.yml
:apiVersion: v1 kind: Pod metadata: name: mysql-pod spec: containers: - name: mysql image: mysql:5.6 ports: - containerPort: 3306 env: - name: MYSQL_ROOT_PASSWORD value: password volumeMounts: - name: mysql-storage mountPath: /var/lib/mysql volumes: - name: mysql-storage persistentVolumeClaim: claimName: mysql-pv-claim
Create the Pod:
kubectl apply -f mysql-pod.yml
Check the status of the pod with
kubectl get pod mysql-pod
. After a few moments it should be in the RUNNING status.You can also verify that the pod is interacting with the filesystem at
/mnt/data
on the node. Log in to the node from the Kube master like this, using the same as the password for the kube master:ssh cloud_user@10.0.1.102
Check the contents of the PersistentVolume directory:
ls /mnt/data
You should see files and directories there related to MySQL. These were created by the pod, meaning that your PersistentVolume and PersistentVolumeClaim are working!