How to share a file from initContainer to base container in Kubernetes

11/9/2021

I have created a custom alpine image (alpine-audit) which includes a jar file in the /tmp directory. What I need is to use that alpine-audit image as the initContainers base image and copy that jar file that I've included, to a location where the Pod container can access.

My yaml file is like below

apiVersion: v1
kind: Pod
metadata:
  name: init-demo
spec:
  containers:
  - name: nginx
    image: nginx
    ports:
    - containerPort: 80
    volumeMounts:
    - name: workdir
      mountPath: /usr/share/nginx/html
  initContainers:
  - name: install
    image: my.private-artifactory.com/audit/alpine-audit:0.1.0
    command: ['cp', '/tmp/auditlogger-1.0.0.jar', 'auditlogger-1.0.0.jar']
    volumeMounts:
    - name: workdir
      mountPath: "/tmp"
  dnsPolicy: Default
  volumes:
  - name: workdir
    emptyDir: {}

I think there is some mistake in the command line. I assumed initContainer copy that jar file to emptyDir then the nginx based container can access that jar file using the mountPath. But it does not even create the Pod. Can someone point me where it has gone wrong?

-- AnujAroshA
kubernetes

1 Answer

11/9/2021

When you are mouting a volume to a directory in pod, that directory have only content of the volume. If you are mounting emptyDir into your alpine-audit:0.1.0 the /tmp directory becomes empty. I would mount that volume on some other dir, like /app, then copy the .jar from /tmp to /app.

The container is not starting probably because the initContainer failes running the command.

Try this configuration:

apiVersion: v1
kind: Pod
metadata:
  name: init-demo
spec:
  containers:
  - name: nginx
    image: nginx
    ports:
    - containerPort: 80
    volumeMounts:
    - name: workdir
      mountPath: /usr/share/nginx/html
  initContainers:
  - name: install
    image: my.private-artifactory.com/audit/alpine-audit:0.1.0
    command: ['cp', '/tmp/auditlogger-1.0.0.jar', '/app/auditlogger-1.0.0.jar'] # <--- copy from /tmp to new mounted EmptyDir
    volumeMounts:
    - name: workdir
      mountPath: "/app" # <-- change the mount path not to overwrite your .jar
  dnsPolicy: Default
  volumes:
  - name: workdir
    emptyDir: {}
-- Cloudziu
Source: StackOverflow