Kubernetes Persistant Volume overwrites image data

4/14/2021

I have a pod that reads from an image that contains data within var/www/html. I want this data to be stored in a persistent volume. This is my deployment yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
    name: app
spec:
    replicas: 1
    selector:
        matchLabels:
            container: app
    template:
        metadata:
            labels:
                container: app
        spec:
            containers:
                - name: app
                  image: my/toolkit-app:working
                  ports:
                      - containerPort: 80
                  volumeMounts:
                      - mountPath: /var/www/html
                        name: toolkit-volume
                        subPath: html
            volumes:
                - name: toolkit-volume
                  persistentVolumeClaim:
                      claimName: azurefile
            imagePullSecrets:
                - name: my-cred

However when I look into the pod I can see the directory is empty:

Empty directory

If I comment out the persistent volume:

              #volumeMounts:
              #    - mountPath: /var/www/html
              #      name: toolkit-volume
              #      subPath: html

I can see that the image data is there:

Non-empty directory

So it seems like the persistent volume is overwriting the existing directory - is there a way round this? Ideally I want /var/www/html to be stored in a separate volume and for any existing files within the image to be stored there too.

-- Lee
kubernetes

1 Answer

4/14/2021

This is more a problem of visibility: If you mount an empty volume at a specific path, you won't be able to see, what was placed there in the container image.

From your question I assume that you want to be able to rollout updates by the means of a new container image, but at the same time retain variable data, that was created at the same directory from your application.

You could achieve this with the following method: Use an init container with the same image and mount your persistent directory to a different path, for example /data As command for the init container copy the contents of /var/www/html to /data.

In the regular container image use the mount you already have, it will contain your variable data and the updated data from the init container.

-- Thomas
Source: StackOverflow