Kubernetes, how to link a PersistentVolume to a volumeClaim

11/7/2018

I'm newbie in the Kubernetes world and I try to figure it out how a volumeClaim or volumeClaimTemplates defined in a StatefulSet can be linked to a specific PersistentVolume.

I've followed some tutorials to understand and set a local PersistentVolume. If I take Elasticsearch as an example, when the StatefulSet starts, the PersistantVolumeClaim is bound to the PersistantVolume.

Like you know, for a local PersistentVolume we must define the local path to the storage destination.

For Elasticsearch I've defined something like this

local:
  path: /mnt/kube_data/elasticsearch

But in a real project, there are more than one persistent volume. So, I will have more than one folder in path /mnt/kube_data. How does Kubernetes select the right persistent volume for a persistent volume claim?

I don't want Kubernetes to put Database data in a persistent volume created for another service.

Here is the configuration for Elasticsearch :

---
apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
  name: elasticsearch-sts
spec:
  serviceName: elasticsearch
  replicas: 1
[...]
    containers:
    - name: elasticsearch
        image: docker.elastic.co/elasticsearch/elasticsearch:6.4.2
        volumeMounts:
        - name: elasticsearch-data
        mountPath: /usr/share/elasticsearch/data
volumeClaimTemplates:
- metadata:
    name: elasticsearch-data
  spec:
    accessModes: [ "ReadWriteOnce" ]
    storageClassName: local-storage
    resources:
        requests:
        storage: 10Gi
---
apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-elasticsearch
spec:
  capacity:
    storage: 10Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
storageClassName: local-storage
local:
    path: /mnt/elasticsearch
nodeAffinity:
    required:
    nodeSelectorTerms:
    - matchExpressions:
        - key: node-role.kubernetes.io/master
        operator: Exists
---
-- Waldo
kubernetes
persistent-volume-claims
persistent-volumes

1 Answer

11/7/2018

You need ClaimRef in the persistent volume definition which have the PVC name to which you want to bind your PV. Also, ClaimRef in PV should have the namespace name where PVC resides because PV's are independent to namespace while PVC aren't. So a same name PVC can exist in two different namespace, hence it is mandatory to provide namespace along with PVC name even when PVC resides in default namespace.

You can refer following answer for PV,PVC and statefulset yaml files for local storage.

Is it possible to mount different pods to the same portion of a local persistent volume?

Hope this helps.

-- Prafull Ladha
Source: StackOverflow