Home > Software engineering >  How to execute a binary and use sleep pod after some time together in kubernetes
How to execute a binary and use sleep pod after some time together in kubernetes

Time:12-09

I have a use case that my "./main" binary should run inside the pod and stop after some time (90 seconds) before launching a new pod by the cronJob object.

But I am not confused about how to add both sleep and run my binary in the background together. Please suggest a good approach to this and excuse me for any wrong syntax.

Dockerfile

FROM golang:alpine
WORKDIR /app
COPY main /app
RUN  apk update && apk add bash
CMD  ["./main &"]

---
cronjob.yaml

apiVersion: batch/v1
kind: CronJob
metadata:
  name: cron
  namespace: test-cron
spec:
  schedule: "*/2 * * * *"
  concurrencyPolicy: Replace
  successfulJobsHistoryLimit: 0
  failedJobsHistoryLimit: 0
  jobTemplate:
    spec:
      template:
        spec:
          restartPolicy: OnFailure
          volumes:
          - name: log
            hostPath:
                path: /data/log/test-cron/
          containers:
            - name: test-cron
              image:  test-kafka-0.5
              command: ["sleep", "90"] // By adding this, the sleep command is working but my binary is not running inside my container.

CodePudding user response:

Kubernetes has built-in support for killing a Pod after a deadline; you do not need to try to implement this manually.

In your Dockerfile, set up your image to run the program normally. Do not try to include any sort of "sleep" or "kill" option, and do not try to run the program in the background.

CMD ["./main"]

In the Job spec, you need to set an activeDeadlineSeconds: field.

apiVersion: batch/v1
kind: CronJob
spec:
  jobTemplate:
    spec:
      activeDeadlineSeconds: 90  # <-- add
      template:
        spec:
          containers:
            - name: test-cron
              image:  test-kafka-0.5
              # do not override `command:`

An identical option exists at the Pod level. For your use case this doesn't especially matter, but if the Job launches multiple Pods then there's a difference of whether each individual Pod has the deadline or whether the Job as a whole does.

It looks from the question like you're trying to run this job every two minutes and not have two concurrent copies of it. Assuming the Pod is created and starts promptly, this should accomplish that. If you had a reason to believe the Job would run faster the second time and just want to restart it, the CronJob might not be the setup you're after.

  • Related