Terminate a sidecar container in Kubernetes

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: great-job
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: count
            image: busybox
            command: ["/bin/sh", "-c"]
            args:
              - |
                sleep 2s
                trap "touch /var/log/terminated" EXIT
                i=0; while [ $i -lt 10 ]; do echo "$i: $(date)" >> /var/log/app.log; i=$((i+1)); sleep 1; done
            volumeMounts:
            - name: varlog
              mountPath: /var/log
          - name: count-log
            image: busybox
            command: ["/bin/sh", "-c"]
            args:
            - |
              tail -f /var/log/app.log & CHILD_PID=$!
              (while true; do if [[ -f "/var/log/terminated" ]]; then kill $CHILD_PID; echo "Killed $CHILD_PID because the main container terminated."; fi; sleep 1; done) &
              wait $CHILD_PID
              if [[ -f "/var/log/terminated" ]]; then exit 0; echo "Job completed. Exiting..."; fi
            volumeMounts:
            - name: varlog
              mountPath: /var/log
          volumes:
          - name: varlog
            emptyDir: {}
          restartPolicy: OnFailure
      backoffLimit: 5
---
kubectl apply -f great-job.yaml
➜  ~ kubectl get pods
NAME                         READY   STATUS      RESTARTS   AGE
great-job-1575331260-mjl68   0/2     Completed   0          2m28s
great-job-1575331320-p6srg   0/2     Completed   0          88s
great-job-1575331380-xqk49   0/2     Completed   0          28s
➜  ~ kubectl logs -f great-job-1575331380-xqk49 -c count-log
0: Tue Dec  3 00:03:12 UTC 2019
1: Tue Dec  3 00:03:13 UTC 2019
2: Tue Dec  3 00:03:14 UTC 2019
3: Tue Dec  3 00:03:15 UTC 2019
4: Tue Dec  3 00:03:16 UTC 2019
5: Tue Dec  3 00:03:17 UTC 2019
6: Tue Dec  3 00:03:18 UTC 2019
7: Tue Dec  3 00:03:19 UTC 2019
8: Tue Dec  3 00:03:20 UTC 2019
9: Tue Dec  3 00:03:21 UTC 2019
Killed 7 because the main container terminated.

Based on Medium from Koji Nishikiori

You can download Gist


Jose Bovet Derpich

Linux and Coffee Lover, Father of @SlackwareSecAdv - Software Engineer at Walmart