Run a Container with a readOnlyRootFilesystem

One approach to running a container with readOnlyRootFilesystem: true is to use writable volume mounts (e.g. emptyDir, generic ephemeral volumes, etc.) and then copy those directories in from the main image using an initContainer; for example, for a Deployment:

  1. Create an initContainer using the same IMAGE as your main container, share a volumeMount (e.g. named scratch) between your main container and the initContainer, mount each desired writable folder in the initContainer under an arbitrary directory (e.g. /copy) within the scratch mount and at an arbitrary subPath, recursively copy each image's original directory contents into each mountPath during initContainer execution, and finally use these same subPath mountPaths to mount these writable directories in the main container:
    spec:
      template:
        spec:
          initContainers:
            - name: initcopy
              image: IMAGE
              volumeMounts:
                - name: scratch
                  mountPath: /copy/AppServer
                  subPath: appserver
                - name: scratch
                  mountPath: /copy/tmp
                  subPath: tmp
                - name: scratch
                  mountPath: /copy/home
                  subPath: home
              command:
                - /bin/sh
              args:
                - '-c'
                - "mkdir -p /copy && cp -rv /opt/IBM/WebSphere/AppServer /copy/ && cp -rv /tmp /copy/ && cp -rv /home/was /copy/"
          containers:
            - volumeMounts:
                - name: scratch
                  mountPath: /opt/IBM/WebSphere/AppServer
                  subPath: appserver
                - name: scratch
                  mountPath: /tmp
                  subPath: tmp
                - name: scratch
                  mountPath: /home/was
                  subPath: home
          volumes:
            - name: scratch
              emptyDir: {}
  2. Configure readOnlyRootFilesystem: true