<p>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.</p>

<p>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.</p>

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

<p>For Elasticsearch I've defined something like this </p>

<pre><code>local:
  path: /mnt/kube_data/elasticsearch
</code></pre>

<p>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? </p>

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

<p>Here is the configuration for Elasticsearch :</p>

<pre><code>---
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
---
</code></pre>

<p>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.</p>

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

<p><a href="https://stackoverflow.com/questions/52948124/is-it-possible-to-mount-different-pods-to-the-same-portion-of-a-local-persistent/52952505#52952505">Is it possible to mount different pods to the same portion of a local persistent volume?</a></p>

<p>Hope this helps.</p>
