Encountering CrashLoopBackOff with Exit Code 0 while Running Python Script

461 Views Asked by At

I'm currently running a python script which has only a print statement.

print("Completed")

The python code will be deployed on kubernetes using Dockerfile and a Deployment YAML File.

Dockerfile:

FROM python:3.9   
WORKDIR /app  
COPY Test.py /app/Test.py   
RUN python3 -m pip install --upgrade pip    
ENTRYPOINT ["python"]   
CMD ["Test.py"]   

Deployment YAML File:

apiVersion: apps/v1   
kind: Deployment   
metadata:  
  name: test-01   
spec:   
  replicas: 1   
  selector:   
    matchLabels:   
      bb: web   
  template:   
    metadata:   
      labels:   
        bb: web   
    spec:   
      containers:   
      - name: test-01   
        image: testrepo/testingpy:latest   

The pod will be created, will succesfully run and also show the reason for Termination is because it is Completed with exit code 0 (While exploring the description of the pod).

State:          Waiting
  Reason:       CrashLoopBackOff
Last State:     Terminated
  Reason:       Completed
  Exit Code:    0

After a few seconds the pod will go into CrashLoopBackOff Warning State with the reason "Back-off restarting failed container". The logs for the pod gives information only if there is any printed statements or error while running the code.

kubectl logs etl-patient-c5d44fcc-scc9s --all-containers   
Completed

The kubernetes pod has no reason to go into CrashLoopBackOff state. The pod must execute the script and stay as completed.

Changes Tried.

  1. Tried to manipulate the YAML file with restartPolicy: OnFailure but it raised an error while deploying.
  2. Tried with different python versions which also didn't change the outcome.

P.S The indentation of the YAML file is not visible properly but the indentation of the YAML file is correct.

1

There are 1 best solutions below

0
On

K8s Deployment, StatefulSet and DaemonSet resources is used for handling long running applications (e.g backend, frontend, microservices, web servers etc) which is why it only supports restartPolicy is Always. In your case, the container running inside the Pod finishes after running the print("Completed") statement instead of running for continously.

You've 3 choices:

  1. Use Job type resource instead of Deployment. K8s jobs run only 1 time i.e they finish after completion.
  2. Use simple Pod resource with restartPolicy set to Never
  3. Add some additional code which keeps your python script in running condition like sleep, while loop or HTTP server (Flask, Django etc)

Checkout these links for further details: