Mount volumes as non root user in docker container

3/28/2019

I want to mount a volume in the docker container as a non root user. I am using the following (k8s.yaml) -

volumeMounts:
        - name: volume-to-be-mounted
          mountPath: /location
volumes:
        - name:  volume-to-be-mounted
          hostPath:
            path: path
            type: DirectoryOrCreate

This volume is mounted as root inside the container. But I want to mount it as non-root. Is there any way of doing this? I can also use the https://docs.docker.com/storage/volumes/ but I want to mount the same volume on other container (in the same pod) as well.

Some of the solutions that come to mind but don't suit my use case -

  1. change the permissions of the directory in entrypoint (not viable because entrypoint will be run as a non root user.)
  2. https://stackoverflow.com/a/39576814/9081810 I am using k8s.yaml to specify my requirements. I don't know how this solution will fit in.

Possible solutions that can work but I don't know how to do it -

  1. set permissions to 777 while mounting the volume.
-- user2851669
docker
kubernetes

3 Answers

4/1/2019

If you're using kubernetes you can use a security context and set the fsGroup value.

Example from the docs

apiVersion: v1
kind: Pod
metadata:
  name: security-context-demo
spec:
  securityContext:
    runAsUser: 1000
    fsGroup: 2000
  volumes:
  - name: sec-ctx-vol
    emptyDir: {}
  containers:
  - name: sec-ctx-demo
    image: gcr.io/google-samples/node-hello:1.0
    volumeMounts:
    - name: sec-ctx-vol
      mountPath: /data/demo
    securityContext:
      allowPrivilegeEscalation: false

If you're just using docker ... well there's been an open issue since 2013

-- Graham
Source: StackOverflow

4/2/2019

You want to mount the same volume on other container (in the same pod) as well.
I don't think you can do this.
The definition of pod is:A pod (as in a pod of whales or pea pod) is a group of one or more containers (such as Docker containers), with shared storage/network, and a specification for how to run the containers.
more detail: https://kubernetes.io/docs/concepts/workloads/pods/pod/

-- S.J
Source: StackOverflow

3/28/2019

you can consider running init container as a root user. have init container and main container share the same volume. from init container update the ownership of the volume

-- P Ekambaram
Source: StackOverflow