Create storage class and pv that consumes local storage

To make local storage available to any pod that requests storage in Kubernetes, you can use a Kubernetes feature called a StorageClass. A StorageClass is an abstraction layer that enables dynamic provisioning of storage resources for Kubernetes pods.

To create a StorageClass that uses local storage, you can follow these general steps:

  • Identify the local storage device that you want to use for Kubernetes pods.
  • Create a PersistentVolume object that represents the local storage device. Here’s an example YAML file for a PersistentVolume that uses local storage:
# local-pv.yaml
apiVersion: v1
kind: PersistentVolume
metadata:
  name: local-pv
spec:
  capacity:
    storage: 20Gi
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  storageClassName: local-storage
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: kubernetes.io/hostname
          operator: In
          values:
          - node-01
  local:
    path: /mnt/local-storage

In this example, the PersistentVolume has a capacity of 20GB and uses the local storage path “/mnt/local-storage”.

  • Create a StorageClass object that references the PersistentVolume you just created. Here’s an example YAML file for a StorageClass that uses the “local-storage” PersistentVolume:
# sc-local-storage.yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: local-storage
provisioner: kubernetes.io/no-provisioner
volumeBindingMode: WaitForFirstConsumer
reclaimPolicy: Retain

In this example, the StorageClass has a provisioner value of “kubernetes.io/no-provisioner”, which means that it won’t dynamically provision new PersistentVolumes. Instead, it will use the “local-pv” PersistentVolume that you created earlier.

  • Once you’ve created the StorageClass, you can use it in your Kubernetes pod definitions to request local storage. Here’s an example YAML file for a pod that requests 1GB of local storage using the “local-storage” StorageClass:
  • yaml
# pod-example.yaml
apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
containers:
- name: my-container
image: my-image
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
persistentVolumeClaim:
claimName: my-pvc
storageClassName: local-storage

In this example, the pod requests local storage using a PersistentVolumeClaim with a storageClassName of “local-storage”. The pod’s container then mounts the PersistentVolumeClaim at the “/data” mount path.

By following these steps, you can make local storage available to any Kubernetes pod that requests storage using the “local-storage” StorageClass.