Making Springboot application Pod to be deleted automatically

426 Views Asked by At

I am trying to deploy Springboot application on Kubernetese and I don't want Pod to run endlessly. As soon as the process gets finised, I want pod to be terminated by itself. Now, because of some business logic, we are generating token at each 45 minutes interval using @Scheduled(FixedRateString...) in our Springboot application, it means the process would keep running. To make sure our process gets terminated, we are using System.exit(0) at the end of the application.

I deployed code using below deployment.yml file. As soon as the process is getting terminated, I am seeing the new Pod getting up again , how can I make sure it gets terminate/deleted automatically as soon as the process finished.

deployment.yml

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    tier: pred-d
    app: test-prov-img
  name: test-prov-img
spec:
  selector:
    matchLabels:
      app: test-prov-img
  replicas: 1
  template:
    metadata:
      labels:
        app: test-prov-img
    spec:
      containers:
        - image: docker.repo1.com/apps/test-prov-img:1.2
          imagePullPolicy: Always
          name: test-prov-img
          ports:
            - containerPort: 8080
              name: service
              protocol: TCP
          envFrom:
            - configMapRef:
                name: configmap
          resources:
            limits:
              cpu: 1
              memory: 1.25Gi
            requests:
              cpu: 0.1
              memory: 0.25Gi

Please suggest what changes I have to do in the deployment.yml to make the Pod termianted/deleted automatically.

1

There are 1 best solutions below

3
On

A method annotated with @Scheduled is designed to repeat. Instead of scheduling something, just make the application do whatever it needs to do and then finish. One option can be to add a CommandLineRunner implementation that performs the work that is currently being done by the @Scheduled method.

@Component
public class TaskPerformer implements CommandLineRunner {

    @Override
    // @Scheduled(fixedRateString = ...) We no longer need this
    public void run(String... args) {
        // TODO: Generate token here
    }
}

Then, you can convert your application into a Kubernetes CronJob which you can instruct to run every 45 minutes. That CronJob will then start up on time, run the application which generates a token, and then shut itself down.