How to make a k8s pod exits itself when the main container exits?

9/24/2019

I am using a sidecard pattern for a k8s pod within which there're two containers: the main container and the sidecar container. I'd like to have the pod status depends on the main container only (say if the main container failed/completed, the pod should be in the same status) and discard the sidecard container.

Is there an elegant way to doing this?

-- injoy
kubernetes
kubernetes-pod
microservices

2 Answers

9/25/2019

Unfortunately the restartPolicy flag applies to all containers in the pod so the simple solution isn’t really going to work. Are you sure your logic shouldn’t be in an initContainer rather than a sidecar? If it does need to be a sidecar, have it sleep forever at the end of your logic.

-- coderanger
Source: StackOverflow

9/25/2019

As per documentation:

Pod is running and has two Containers. Container 1 exits with failure.

Log failure event.

If restartPolicy is:

  • Always: Restart Container; Pod phase stays Running.
  • OnFailure: Restart Container; Pod phase stays Running.
  • Never: Do not restart Container; Pod phase stays Running.

If Container 1 is not running, and Container 2 exits:

Log failure event.

If restartPolicy is:

  • Always: Restart Container; Pod phase stays Running.
  • OnFailure: Restart Container; Pod phase stays Running.
  • Never : Pod phase becomes Failed.

As workaround (partial solution for this problem) with restartPolicy: Never - you can apply the result of livenees probe from the main container to the sidecar container (using using exec, http or tcp probe).

It's not the good solution while working with microservices.

example:

apiVersion: v1
kind: Pod
metadata:
  labels:
    test: liveness
  name: liveness-exec
spec:
  containers:
  - name: liveness1
    image: k8s.gcr.io/busybox
    args:
    - /bin/sh
    - -c
    - touch /test-pd/healthy; sleep 30; rm -rf /test-pd/healthy; sleep 30
    livenessProbe:
      exec:
        command:
        - cat
        - /test-pd/healthy
      initialDelaySeconds: 5
      periodSeconds: 5
    volumeMounts:
    - mountPath: /test-pd
      name: test-volume
  - name: liveness2
    image: k8s.gcr.io/busybox
    args:
    - /bin/sh
    - -c
    - sleep 120
    livenessProbe:
      exec:
        command:
        - cat
        - /test-pd2/healthy
      initialDelaySeconds: 5
      periodSeconds: 5
    volumeMounts:
    - mountPath: /test-pd2
      name: test-volume
  restartPolicy: Never
  volumes:
  - name: test-volume
    hostPath:
      # directory location on host
      path: /data
      type: Directory

Please let me know if that helped.

-- Hanx
Source: StackOverflow