How to Attach a Persistent Volume to a Kubernetes Pod on AKS

This blog post will show you how to create a persistent storage volume and attach it to a Kubernetes Pod running on an AKS cluster.

When it comes to using persistent volumes on a Kubernetes cluster and attaching them to Pods the process is well organised as you will see below.

Process

Attaching storage to a Kubernetes pod is a two-way process, we first need to create a volume claim and then use it.

Create a Persistent Volume Claim

The first step in the process is to create a volume claim that will define the volume type and size.

To create the claim, I will use the following.YAML file. In my case, I am creating a volume that will use Azure premium SSD disk and will have 2GB size limit.

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: azure-premium-disk
spec:
  accessModes:
  - ReadWriteOnce
  storageClassName: managed-premium
  resources:
    requests:
      storage: 2Gi

After saving the file and connecting to my AKS cluster using Azure CLI I will run the following command:

kubectl apply -f volume_claim.yaml 

After runing the command I can check if the volume was created using the following command.

kubectl get persistentvolumeclaims

Deploy Pod with Attached Volume

After my storage claim has been created, I will go ahead and create a Pod and attach the persistent volume to it.

The below file, will use the above volume claim (azure-premium-disk) and attach it to my Linux nginx pod.

apiVersion: v1
kind: Pod
metadata:
   name: nginx
spec:
  volumes:
    - name: "appdata"
      persistentVolumeClaim:
         claimName: "azure-premium-disk"
  containers:
    - image: nginx:latest
      name: nginx
      volumeMounts: 
        - mountPath: "/data"
          name: "appdata"
      ports:
        - containerPort: 8080
          name: http
          protocol: TCP 

To apply the Pod and attached volume I will run the apply command as shown below.

kubectl apply -f deploy.yaml 

To check if the volume is available inside the Pod, I will run the following command.

kubectl exec nginx -- ls

To check the volume claim use.

kubectl get persistentvolumeclaims

Processing…
Success! You're on the list.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.