When you trying to run a simple container with shell (/bin/bash) on a Kubernetes cluster, the container exits when its main process exits. you will see your pod in completed state. To keep your pod/container always running on kubernetes, you need to provide your container a task that will never finish. There are several ways to accomplish that.
In order to keep a POD running it should to be performing certain task, otherwise Kubernetes will find it unnecessary, therefore it stops. There are many ways to keep a POD running.
The following are the two ways:
- Running sleep command while running the container.
- Running an infinite loop inside the container.
Although the first option is easier than the second one and may suffice the requirement, it is not the best option. As, there is a limit as far as the number of seconds you are going to assign in the sleep command. But a container with infinite loop running inside it never exits.
1. Sleep Command
apiVersion: v1
kind: Pod
metadata:
name: ubuntu
spec:
containers:
- name: ubuntu
image: ubuntu:latest
# Just spin & wait forever
command: [ "/bin/bash", "-c", "--" ]
args: [ "while true; do sleep 30; done;" ]
2. Infinite Loop
apiVersion: v1
kind: Pod
metadata:
name: busybox
labels:
app: busybox
spec:
containers:
- name: busybox
image: busybox
ports:
- containerPort: 80
command: ["/bin/sh", "-ec", "while :; do echo '.'; sleep 5 ; done"]
Also, for some distrobutions, sleep with infinity parameters would be better,(not working for busybox)
apiVersion: v1
kind: Pod
metadata:
name: ubuntu
spec:
containers:
- name: ubuntu
image: ubuntu:latest
# Just sleep forever
command: [ "sleep" ]
args: [ "infinity" ]
3. Sleep in Dockerfile
CMD exec /bin/bash -c "trap : TERM INT; sleep infinity & wait"
or
CMD ["sh", "-c", "tail -f /dev/null"]