'Directories creation inside the Kubernetes Persistent Volume

How would we create a directory inside the kubernetes persistent volume to mount to use in the container as subPath ? eg: mysql directory should be created while claiming the persistent volume



Solution 1:[1]

I would probably put an init container into my podspec that simply mounts the volume and runs a mkdir -p to create the directory and then exit. You could also do this in the target container itself with some kind of script.

https://kubernetes.io/docs/concepts/workloads/pods/init-containers/

Solution 2:[2]

I think you could use the readinessProbe where you could use the execAction to create the sub folder. It will make sure your folder ready before container is ready to accept requests.

Otherwise you could use the COMMAND option to create it. But that will be executed after container starts.

Solution 3:[3]

This is how I implemented the wise solution of @brett-wagner with initContainer and mkdir -p. I create two sub-diretctories, my-app-data and my-app-media, in my NFS server volume /exports:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-nfs-server-deploy
  labels:
    app: my-nfs-server
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my-nfs-server
  template:
    spec:
      containers:
      - name: my-nfs-server-cntr
        image: k8s.gcr.io/volume-nfs:0.8
        volumeMounts:
        - name: my-nfs-server-exports
          mountPath: "/exports"
      initContainers:
      - name: volume-dirs-init-cntr
        image: busybox:1.35
        command:
        - "/bin/mkdir"
        args:
        - "-p"
        - "/exports/my-app-data"
        - "/exports/my-app-media"
        volumeMounts:
        - name: my-nfs-server-exports
          mountPath: "/exports"
      volumes:
      - name: my-nfs-server-exports
        persistentVolumeClaim:
          claimName: my-nfs-server-pvc

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brett Wagner
Solution 2 Aditya Bhuyan
Solution 3 Martin Tovmassian