<p>I'm trying to run a tomcat container in K8S with a non-root user, to do so I set User 'tomcat' with the appropriate permission in Docker Image. I have a startup script that creates a directory in /opt/var/logs (during container startup) and also starts tomcat service.</p>
<pre><code>#steps in Dockerfile
#adding tomcat user and group and permission to /opt directory
addgroup tomcat -g 1001 &amp;&amp; \
adduser -D -u 1001 -G tomcat tomcat &amp;&amp; \
chown -R tomcat:tomcat /opt

#switch user
User tomcat

</code></pre>
<p>The pod runs fine in K8S when deployed using deployment without any volume mapped.</p>
<p>But I get a permission denied error (permission denied: creating directory /opt/var/logs/docker/) from the startup script, which fails to create a directory when I map the deployment with the persistent volume claim, even though I set the fsgroup as explained here, https://kubernetes.io/docs/tasks/configure-pod-container/security-context/.</p>
<p>I have a persistent volume of type hostPath.</p>
<p>The deployment definition is as below.</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: ms-tomcat
  namespace: ms-ns
  labels:
    app: tomcat
spec:
  selector:
    matchLabels:
      app: tomcat
  template:
    metadata:
      labels:
        app: tomcat
    spec:
      securityContext:
          fsGroup: 2000
          runAsUser: 1001
          runAsGroup: 1001
      containers:
      - name: tomcat
        image: docker-registry.test.com/tomcat:1.2
        volumeMounts:
        - name: logging-volume
          mountPath: /opt/var/logs/docker
      imagePullSecrets:
      - name: test
      volumes:
      - name: logging-volume
        persistentVolumeClaim:
          claimName: nonroot-test-pvc
</code></pre>
<p>PVC</p>
<pre><code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name:  nonroot-test-pvc
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 2Gi
  storageClassName: local-node-sc
  volumeName: nonroot-test-pv
</code></pre>

<p>you need to run an initcontainer that will execute chmod 777 on the mounted volume to to be able to use the volume in a container with a non root user</p>
<p>this can be easily done by creating an init container from an alpine image</p>
<p>you can face this problem when trying to use longhorn as your storage class</p>
<p>like this:</p>
<pre><code>spec:
  initContainers:
      - name: permission-init
        image: alpine:3.16.0
        command:
        - sh
        - -c
        - (chmod 777 /data)
        volumeMounts:
          - name: files
            mountPath: /data
</code></pre>
