Replace Container Directory in OpenShift

A directory inside a container may be replaced without re-building an image by mounting a volume on the target directory and populating that volume within an initContainer.

  1. Determine the directory you want to replace. If needed, oc exec into the container and find the target directory.
  2. Edit the pod or deployment YAML. For example:
    oc edit deployment deployment1
  3. Add a shared, ephemeral volume to the pod. For example:
    spec:
      volumes:
      - name: shared-data
        emptyDir: {}
  4. Add an initContainer that mounts the shared volume and sleeps for enough time to upload the directory to it. For example:
    spec:
      initContainers:
      - name: initcontainer
        image: fedora
        command: ["/bin/sh", "-c", "sleep 180"]
        volumeMounts:
        - mountPath: /tmp/mounted
          name: shared-data
  5. Add the shared volume to the target container at the target directory. For example:
    spec:
      containers:
      - name: ...
        volumeMounts:
        - mountPath: /opt/java/openjdk
          name: shared-data
  6. Save the YAML and the pod/deployment will restart
  7. Wait for the pod to restart and show in an Init state. For example:
    $ oc get pods
    NAME                          READY   STATUS     RESTARTS   AGE
    liberty1-b86b797cb-d42nd      0/1     Init:0/1   0          3s
  8. Copy the files for the destination directory into the init container. For example:
    oc cp -c initcontainer JDKdebugbuild.tar.gz liberty1-b86b797cb-d42nd:/tmp/
  9. Remote into the init container and organize the target directory under /tmp/mounted as needed. For example:
    $ oc exec -it liberty1-b86b797cb-d42nd -c initcontainer -- bash
      $ cd /tmp
      $ tar xzf JDKdebugbuild.tar.gz
      $ mv jdk/* /tmp/mounted/
  10. Wait for the sleep time of the init container to elapse and the target container will start.
  11. If required, remote into the target container and confirm the target directory has been updated properly. For example:
    $ oc exec -it liberty1-b86b797cb-d42nd -- bash
      $ /opt/java/openjdk/bin/java -version
      OpenJDK Runtime Environment (build 11.0.21-internal+0-adhoc..BuildJDK11x86-64linuxPersonal)
      [...]