I'm now trying to run a simple container with shell(/bin/bash) on Kubernetes Cluster.
I thought that there is a way to keep container running on docker container by using pseudo-tty and detach option(-td
option on docker run
command).
For Example
$ sudo docker run -td ubuntu:latest
Is there any option like this in kubernetes?
I've tried running container by using kubectl run-container
command like
kubectl run-container test_container ubuntu:latest --replicas=1
but container exits in few seconds (just like launching with docker run
command without options I mentioned above.) and ReplicationController launches it again repeatedly.
Is there any way to keep container runnning on Kubernetes like -td options in docker run
command?
In your Dockerfile use this command:
CMD ["sh", "-c", "tail -f /dev/null"]
Build your docker image.
kubectl run debug-container -it --image=<your-image>
I was able to get this to work with the command
sleep infinity
in kubernetes, which will keep the container open. See this answer for alternatives when that doesn't work.You could use this CMD in your
Dockerfile
:This will keep your container alive until it is told to stop. Using trap and wait will make your container react immediately to a stop request. Without trap/wait stopping will take a few seconds.
For busybox based images (used in alpine based images) sleep does not know about the infinity argument. This workaround gives you the same immediate response to a
docker stop
like in the above example:A container exits when its main process exits. Doing something like:
to hold the container open is frankly a hack that should only be used for quick tests and examples. If you just want a container for testing for a few minutes, I would do:
Which has the advantage that the container will automatically exit if you forget about it. Alternatively, you could put something like this in a
while
loop to keep it running forever, or just run an application such astop
. All of these should be easy to do in Kubernetes.The real question is why would you want to do this? Your container should be providing a service, whose process will keep the container running in the background.
In my case, a pod with an initContainer failed to initialize. Running
docker ps -a
and thendocker logs exited-container-id-here
gave me a log message whichkubectl logs podname
didn't display. Mystery solved :-)Containers are meant to run to completion. You need to provide your container with a task that will never finish. Something like this should work: