Kubernetes: how to set VolumeMount user group and file permissions
I ended up with an initContainer
with the same volumeMount
as the main container to set proper permissions, in my case, for a custom Grafana image.
This is necessary when a container in a pod is running as a user other than root
and needs write permissions on a mounted volume.
initContainers:
- name: take-data-dir-ownership
image: alpine:3
# Give `grafana` user (id 472) permissions a mounted volume
# https://github.com/grafana/grafana-docker/blob/master/Dockerfile
command:
- chown
- -R
- 472:472
- /var/lib/grafana
volumeMounts:
- name: data
mountPath: /var/lib/grafana
- https://kubernetes.io/docs/concepts/workloads/pods/init-containers/
Update: Note that it might suffice to run chown
without the -R
(recursive) flag, since the permissions will generally be persisted across pod restarts. This will be desirable if there are large amounts of files in the volume, as it will take time to process all of them (depending on the resources
limits that are set for the initContainer
).
The Pod Security Context supports setting an fsGroup
, which allows you to set the group ID that owns the volume, and thus who can write to it. The example in the docs:
apiVersion: v1
kind: Pod
metadata:
name: hello-world
spec:
containers:
# specification of the pod's containers
# ...
securityContext:
fsGroup: 1234
More info on this is here