Search code examples
kubernetesvolumespersistent-volume-claims

How can I mount files in the same sub path in k8s deployment?


I have these volume mounts right now defined in my deployment,

volumeMounts:
        - name: website-storage
          mountPath: /app/upload
          readOnly: false
          subPath: foo/upload
        - name: website-storage
          mountPath: /app/html
          readOnly: true
          subPath: foo/html/html

Now I want to mount another path from my PVC into /app/html/website-content and this is what I attempted with,

volumeMounts:
        - name: website-storage
          mountPath: /app/upload
          readOnly: false
          subPath: foo/upload
        - name: website-storage
          mountPath: /app/html
          readOnly: true
          subPath: foo/html/html
        - name: website-storage
          mountPath: /app/html/website-content
          readOnly: true
          subPath: foo/website-content

This does not work and gives an error during mounting. Is it possible to do this? Do I have to explicitly create the website-content folder prior to mounting it? Thanx in advance!


Solution

  • The cause of the issue is that during pod initialization there is an attempt to create directory website-content in the /app/html location which will cause error as the /app/html is mounted read only.

    You cannot create a folder in the read only system that means you can't mount a volume as the folder doesn't exist, but if there was already the folder created, you can mount the volume.

    So all you need is just to create a directory website-content in the foo/html/html location on the volume before you attach it into container. Then, as it will be mounted to the /app/html location, there will be directory /app/html/website-content.

    For example, you can use a init container for that. Add this code to your deployment file:

    initContainers:
      - name: init-container
        image: busybox
        volumeMounts:
        - name: website-storage
          mountPath: /my-storage
          readOnly: false
        command: ['sh', '-c', 'mkdir -p /my-storage/foo/html/html/website-content']
    

    When the pod is running, you check mount points on the pod using kubectl describe pod {pod-name}:

    Mounts:
    /app/html from website-storage (ro,path="foo/html/html")
    /app/html/website-content from website-storage (ro,path="foo/website-content")
    /app/upload from website-storage (rw,path="foo/upload")