Step 7: Implementing persistent storage (CSI)

In short
  • Containers are ephemeral, but heavy applications require persistence.
  • Principle of persistent storage under K8S: PV, PVC, StorageClass.
  • Implementing a CSI driver (and CPI) suitable for the platform.
  • Testing volume creation.

Legacy version of the Kubernetes cookbook

This article is part of the first version of the cookbook (VMware and PhotonOS). A new version, on XCP-ng and Rocky Linux, is being published: persistent storage has not yet been covered in it; in the meantime, the CSI NFS/SMB article covers this topic. The article remains online for reference.

Introduction

Now that the cluster is operational, it will be necessary to add addons to enable it to provide certain functionalities.

Among the frequently expressed needs regarding container usage, support for persistent storage is a common one. Indeed, containers were originally designed to work with ephemeral data, fitting into a microservice logic where lightness, instantaneity, and multiplicity are important.

However, with the increasing adoption of containerization, we have long since moved towards using heavy applications that often require persistence of data.

In this context, stopping and restarting a container must be accompanied by the associated data.

We can rely on file sharing via protocols such as NFS (Network File System) or SMB (Server Message Block), but this type of access is not always suitable, especially in cases requiring high performance or compatibility.

Sometimes, the containerized application requires a "block" access, as if it were directly mapped to a disk with a standard filesystem.

Principle of persistent storage under K8S

To address storage issues, Kubernetes provides a dedicated object called: PersistentVolume (pv). This can be manipulated directly or preceded by another object named PersistentVolumeClaim (pvc), which allows you to associate a container with a data space that can persist throughout the lifecycle of the pod it is attached to.

If the object is natively supported, its interaction with third-party storage systems depends on the driver deployed within the cluster.

To simplify things, Kubernetes offers a standard called CSI for Container Storage Interface.

In general terms, CSI allows external providers to offer an add-on that enables a Kubernetes cluster to manage a storage system and create pv volumes within it.

For automatic provisioning of pv volumes, a CSI can also be used with a third Kubernetes object called StorageClass (sc).

A sc represents a "class" of storage, which is an available space for hosting volumes.

One or more classes can be declared within the same cluster and can use different CSI add-ons.

This allows us to cover specific needs based on the capabilities offered by the solutions associated with the CSI drivers: performance, redundancy, supported file systems, etc.

Feel free to browse this article, as other explanations are available for CSI.

Once a sc is available, we can create PersistentVolumeClaim (pvc) objects, which describe a storage requirement. These include:

  • A volume size
  • An access type: read-only, read from multiple sources, but write accessible only from a single source, dedicated read/write, etc.

The requirements of the pvc must correspond to the features supported by the sc.

If this is the case, we can have a pv deployed automatically through the pvc, which in turn can provision the requirement expressed in the sc.

We can also forgo using a sc and declare a pv directly, specifying the desired characteristics.

In this case, the volume is not automatically provisioned. Even in this scenario, the pvc can be used, and it will then attempt to find a pre-declared pv that is compatible with the request. If a pv can be called and manipulated directly, it is generally best practice to always go through a pvc.

This logic differentiates between how the volume is provisioned and how the volume is consumed.

The first case is typically handled by administrators, while the second is handled by developers.

When an application deployment is written by a developer, the developer does not need to worry about how their storage needs will be provisioned. They simply express a requirement (volume/type of access) through a pvc, and the final volume assignment (pv) will be managed automatically within the cluster based on the available storage classes or volumes already declared by administrators.

Here is an attempt to outline all of this:

Principle of persistent storage under K8S

Click the image to enlarge.

Implementation

In our situation, we will use the CSI Vsphere driver to utilize datastores declared on an ESXi cluster as a persistent storage source.

For now, we will connect to the first control plane using the current user (bvivi57).

The first thing to do is to check the status of all nodes using the following command:

kubectl get node
Node control

Click the image to enlarge.

Then, we verify that all system components are operational with the following command:

kubectl get pod -n kube-system
System component control

Click the image to enlarge.

If everything is OK, then we can start the installation of the CSI.

As a reminder, all configuration files have been prepared using the Ansible playbook.

Everything has been placed in the cloud directory of the current user.

CSI (Container Storage Interface)

Before deploying the CSI itself, it is necessary to deploy the CPI for Cloud Provider Interface. This is a prerequisite for vSphere CSI because the vCenter to which the cluster will connect to manage volumes is seen as a cloud provider.

The CPI is associated with the file vsphere-cloud-controller-manager.yaml, which is located in ~/kub.coolcorp.priv/cloud/cpi on the first control plane.

Location of the file associated with the CPI

Click the image to enlarge.

Its copy and customization were performed by the Ansible playbook. Very little information has been added.

We simply provide the connection details for vCenter, as well as the elements associated with the vSphere cluster on which the K8S nodes are running. All the details related to the variables used in this file are available in the dedicated Ansible article.

Contents of the vsphere-cloud-controller-manager.yaml file

Click the image to enlarge.

For those who are sensitive to cybersecurity, they will notice that the file contains a dedicated service account created specifically for this purpose, including login and password. This is indeed a file that should not be kept, and you should feel free to delete it once the installation is complete.

Simply type the following command to deploy the CPI:

kubectl apply -f vsphere-cloud-controller-manager.yaml
CPI installation

Click the image to enlarge.

We can then check its status using the following command:

kubectl get pod -n kube-system -o wide
CPI control

Click the image to enlarge.

CSI (Container Storage Interface)

We can now switch to installing the CSI.

Similarly to the CPI, the file preparation was performed using Ansible, and all the necessary files are located in ~/kub.coolcorp.priv/cloud/csi on the first control plane.

Location of the CSI configuration files

Click the image to enlarge.

Unlike the CPI, which is deployed within the kube-system namespace, the CSI requires a dedicated namespace.

We will therefore start by creating this namespace using the following command:

kubectl apply -f namespace.yaml
Creation of the namespace for the CSI

Click the image to enlarge.

The content of the yaml file is very basic and describes the namespace vmware-system-csi.

  
apiVersion: v1
kind: Namespace
metadata:
  name: vmware-system-csi
  

Once this part is complete, as with the CPI, the CSI requires access to vCenter.

We use the same service account (see article here), but this time we will first generate a secret object to store our credentials and information specific to the VMware cluster that we want to use.

The secret must be named vsphere-config-secret and takes the values defined in the csi-vsphere.conf file, which contains the following:

  
[Global]
cluster-id = "kub"


[VirtualCenter "prdvmwvce501.coolcorp.priv"]
insecure-flag = "true"
user = "[email protected]"
password = "monpassword"
port = "443"
datacenters = "Paris"

Simply use the following command to create the directory:

kubectl create secret generic vsphere-config-secret --from-file=csi-vsphere.conf --namespace=vmware-system-csi
Creation of the secret to store the CSI configuration

Click the image to enlarge.

Next, we call the yaml file vsphere-csi-driver.yaml, obtained from VMware (see the article), using the following command: kubectl apply -f vsphere-csi-driver.yaml

Deployment of the vSphere CSI

Click the image to enlarge.

You can verify the successful deployment using the following command:

kubectl get pod -n vmware-system-csi -o wide
Verification of the vSphere CSI deployment

Click the image to enlarge.

If all indicators are green, then you can consider the CSI deployment to be complete.

Tests

To verify that everything is working correctly, we will perform some tests.

The first step is to create a dedicated namespace for deploying a test application using a persistent volume.

The namespace can be created directly without going through a yaml file (like any Kubernetes object).

kubectl create ns dev-demopvdatastore-lan

I have also made it a habit to always create a working directory named after the namespace.

Creation of the working directory

Click the image to enlarge.

Once inside this directory, I create my yaml files.

As explained in the introduction, I use a StorageClass.

To do this, we first identify the datastore ID on vCenter that will be used to host the volumes.

In my case, I have a dedicated datastore named prddtsnfs001. I need to retrieve its location, as this is the value I will declare in the sc.

Retrieval of the datastore location from vCenter

Click the image to enlarge.

My test sc is described in the file 01-sc-datastore.yaml:

 
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
 name: sc-prddtsnfs001
parameters:
 datastoreurl: ds:///vmfs/volumes/852caa3a-c012d513/
allowVolumeExpansion: true
provisioner: csi.vsphere.vmware.com
reclaimPolicy: Retain
volumeBindingMode: Immediate

The file is not complicated to understand. It contains the standard fields apiVersion, Kind, and metadata, which are common to all Kubernetes objects.

We refer to the StorageClass object from the api branch storage.k8s.io/v1, which we will name sc-prddtsnfs001.

In terms of parameters, we set the VMware location for the datastore retrieved previously.

As an optional addition, we allow volume expansion if necessary via allowVolumeExpansion: true.

It is very important to indicate that we are using the vSphere CSI to provision volumes from this storage class via the provisionner: csi.vsphere.vmware.com option.

Finally, an interesting element is the reclaimPolicy: Retain option. This will define how a volume should be handled when its pvc and the application that uses it are deleted.

In this example, Retain indicates that the volume will be retained. The alternative would be to choose Delete. In this case, the data is erased at the same time as the application via the deletion of the pv.

This is a choice specific to each individual and their needs. The advantage of choosing Retain is that you can re-access the data if necessary by remapping the volume.

The disadvantage is that if you do not have a regular cleanup policy, you risk accumulating PersistentVolume over time and consuming space for nothing.

Of course, even with the Retain option, you can later delete a PersistentVolume manually.

Also note that you can choose a default StorageClass. In this case, if nothing is specified at the level of a PersistentVolumeClaim, this one will be used by the cluster.

kubectl apply -f 01-sc-datastore.yaml
Creation of the storage class

Click the image to enlarge.

We can put the pvc into maintenance. It is described in the file 02-pvc-demopvdatastore.yaml, which contains the following:

 
kind: "PersistentVolumeClaim"
apiVersion: "v1"
metadata:
  name: pvc-demopvdatastore
  namespace: dev-demopvdatastore-lan
  labels:
    environment: dev
    network: lan
    application: demopvdatastore
spec:
  accessModes:
    - "ReadWriteOnce"
  resources:
    requests:
      storage: "5Gi"
  storageClassName: sc-prddtsnfs001

It includes a Spec: field where we can specify for this object of type PersistentVolumeClaim, the desired space 5Go and the associated access type, ReadWriteOnce. We are therefore requesting a volume that is accessible for both reading and writing from only one pod at a time.

The most important thing is the reference to the sc created previously to indicate to the pvc to dynamically provision the volume in it.

kubectl apply -f 02-pvc-demopvdatastore.yaml
Creation of the PVC

Click the image to enlarge.

Now it's the application's turn to be deployed via the file 03-deploy-demopvdatastore.yaml.

 
apiVersion: apps/v1
kind: Deployment
metadata:
  name: deploy-demopvdatastore
  namespace: dev-demopvdatastore-lan
  labels:
    environment: dev
    network: lan
    application: demopvdatastore
spec:
  strategy:
    type: Recreate
  selector:
    matchLabels:
      environment: dev
      network: lan
      application: demopvdatastore
  template:
    metadata:
      labels:
        environment: dev
        network: lan
        application: demopvdatastore
    spec:
      nodeSelector:
        network: lan
      containers:
      - name: demo-nginx-with-datastore
        image: nginx:1.27
        resources:
          requests:
            memory: "8Mi"
            cpu: "250m"
          limits:
            memory: "256Mi"
            cpu: 1
        livenessProbe:
          initialDelaySeconds: 5
          periodSeconds: 5
          exec:
           command:
           - ls /usr/share/nginx/html
        ports:
        - containerPort: 80
        volumeMounts:
        - mountPath: "/usr/share/nginx/html"
          name: nginx-data
      volumes:
      - name: nginx-data
        persistentVolumeClaim:
         claimName: pvc-demopvdatastore
    

I won't go into the details of the Deployment object, which itself manages one or more pods, but the idea of this file is to trigger the execution of a container based on the nginx 1.27 image and map a volume to the internal mount point within the container at /usr/share/nginx/html.

At the end of the file, we see a call to the PVC pvc-demopvdatastore, which will generate the volume nginx-data, which in turn will be mounted at /usr/share/nginx/html.

The deployment is done via the following command:

kubectl apply -f 03-deploy-demopvdatastore.yaml

You may notice that during the launch of the PVC and the application, activity is visible from the vCenter. This is normal, since the K8S cluster is able to communicate with the VMware infrastructure to request the creation of a volume in the datastore associated with the storage class used (thanks to the CPI/CSI combination).

Activity viewed from the vCenter side

Click the image to enlarge.

Let's check that the application is running:

kubectl get pod -n dev-demopvdatastore-lan -o wide
Application control

Click the image to enlarge.

Let's go into more detail to see the status of the PVC using the following command:

kubectl get pvc -n dev-demopvdatastore-lan
PVC control

Click the image to enlarge.

It is correctly indicated as bound, meaning it is mapped to a volume.

You can also list the volumes using the following command:

kubectl get pv
PV control

Click the image to enlarge.

Those who are paying attention will notice that I did not specify the namespace for this command. Indeed, PersistentVolume objects are cross-cluster objects and do not belong to a specific namespace, unlike the PersistentVolumeClaim (pvc).

Let's try to actually see if the volume is being used by the application.

To do this, we will enter the context of the container using the following command:

kubectl exec -it deploy-demopvdatastore-5cb5fd6db7-mt54m bash -n dev-demopvdatastore-lan

deploy-demopvdatastore-5cb5fd6db7-mt54m is the name of the pod in which the container is running; its name is generated dynamically and will therefore change each time the pod restarts.

Once inside the context of the container, you can type the command df -h.

Control of mounts from the container

Click the image to enlarge.

This shows us that we have a device /dev/sdb of 5G used for /usr/share/nginx/html.

This is nothing more than our K8S persistent volume, which is seen within the container as a disk mounted in the OS.

This volume is actually a VMDK (a VMware format disk) that is dynamically mapped to the worker that is currently running the pod, which is prdk8snod501. We can find this VMDK at the level of the VM.

VM view

Click the image to enlarge.

All of this automatic mapping is also visible in the vCenter activity logs.

vCenter activity

Click the image to enlarge.

Within the container context, you can navigate to the path /usr/share/nginx/html and create a file named testpv using the command touch testpv.

Creation of a file in the container

Click the image to enlarge.

Next, exit the container context by pressing CTRL+Z.

To continue the experiment, we will now put the node that is running the container into maintenance mode. I won't go into detail, but the following command will allow the cluster to move all the pods from the node prdk8snod501 to other nodes. This is typically what you do when you want to update the server or perform maintenance on it.

kubectl drain --ignore-daemonsets --ignore-daemonsets --delete-emptydir-data prdk8snod501
Maintenance mode for node prdk8snod501

Click the image to enlarge.

As expected, the pod will automatically be started on another eligible node, in this case, prdk8snod502.

Control of pod execution

Click the image to enlarge.

Since the pod has restarted, its name has changed, but you can still enter its context by updating your previous command.

kubectl exec -it deploy-demopvdatastore-5cb5fd6db7-5kjms bash -n dev-demopvdatastore-lan

If you try to access /usr/share/nginx/html, you will find that your previously created file is still there.

Control of the witness file

Click the image to enlarge.

This time, the VMDK is attached to the worker node that took over. It was detached from prdk8snod501 and then reattached to prdk8snod502, directly managed by the Kubernetes cluster. This operation is possible thanks to the configuration of the CPI/CSI and access to vCenter.

VM view

Click the image to enlarge.

To finish, you can delete the deployment, which includes the pod, and therefore the application, as well as the pvc.

kubectl delete -f 03-deploy-demopvdatastore.yaml kubectl delete -f 02-pvc-demopvdatastore.yaml
Deletion of the pod, PVC, and control of the PV

Click the image to enlarge.

However, if you list the volumes using the command kubectl get pv, the volume is still there, but this time it has a status of Released.

This is normal, since the sc from which it originated is configured to obtain volumes with a retention policy set to Retain.

If you really want to free up space and delete the volume, you will need to run an explicit command: kubectl delete pv nom_volume

Deletion of the PV

Click the image to enlarge.

One small operation to complete: don't forget to take the first node, prdk8snod501, out of maintenance mode using the command kubectl uncordon prdk8snod501

Removal from maintenance mode

Click the image to enlarge.

Again, I won't go into detail; a dedicated article will be provided for managing and maintaining nodes in a K8S cluster.

However, bringing the first node online does not mean that the test application will return to it. Since the application has switched to the second node, there is no reason for it to be restarted on the first node.

Conclusion

We have now reached the end of this section dedicated to storage.

I haven't gone into the details of application deployment; that will come later. The goal here was to present the management of persistent storage within a Kubernetes cluster.

I chose the most complete case possible, including a CSI driver and a StorageClass (sc) for dynamic provisioning of PersistentVolume (pv) via PersistentVolumeClaim (pvc).

It is possible to do it more simply, especially for mapping storage spaces based on file sharing like NFS or CIFS.

You can also map local folders and mount points to a node. In this case, the data stored there will not be found if the application restarts on another worker.

The advantage of the logic presented here is that it is close to what you can find in production.

Here, the CSI is linked to vSphere, and I know that VMware is no longer necessarily a solution to rely on.

But the example shown here could very well apply to other ecosystems.

The use of a CSI driver, sc, pvc, and pv is absolutely not exclusive to VMware. In fact, this is the most important thing to understand here.

Changing storage solutions, except for deploying a new CSI and updating your StorageClass (sc), will have no impact on the deployment logic of your applications.

Even migrating from an on-premises infrastructure to a cloud infrastructure will retain this operating logic, except perhaps that in the cloud, you may not necessarily have the same choice of CSI providers.

If you want to detach yourself from any specific manufacturer/provider, you can very well use a storage infrastructure solution like CEPH.

This type of ecosystem works very well with K8S and allows you to have both file sharing and block storage, but it requires some knowledge and additional administrative overhead.

Conversely, if you want to leverage traditional storage arrays, such as those from NetAPP, then you can also use their CSI implementation, which allows the cluster to provision volumes directly on their equipment.

Regardless of what happens, you should always aim to identify a solution for providing persistent storage within your Kubernetes clusters. The key is to stick with what you know and/or are proficient in, or alternatively, start from a new requirement if that's something you're interested in.

For the rest of this cookbook, please refer to this.