Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run a container from the command line in Kubernetes (like docker run)?

Tags:

kubernetes

I would like to run a one-off container from the command line in my Kubernetes cluster. The equivalent of:

docker run --rm -it centos /bin/bash 

Is there a kubectl equivalent?

like image 313
Dmitry Minkovsky Avatar asked Jun 23 '17 04:06

Dmitry Minkovsky


People also ask

How do I run a docker container from the command line?

The basic syntax for the command is: docker run [OPTIONS] IMAGE [COMMAND] [ARG...] You can run containers from locally stored Docker images. If you use an image that is not on your system, the software pulls it from the online registry.

What does Kubernetes use to run containers?

Container runtimes The container runtime is the software that is responsible for running containers. Kubernetes supports container runtimes such as containerd, CRI-O, and any other implementation of the Kubernetes CRI (Container Runtime Interface).


2 Answers

The kubectl equivalent of

docker run --rm -it centos /bin/bash 

is

kubectl run tmp-shell --restart=Never --rm -i --tty --image centos -- /bin/bash 

Notes:

  • This will create a Pod named tmp-shell. If you don't specify --restart=Never, a Deploment will be created instead (credit: Urosh T's answer).

  • --rm ensures the Pod is deleted when the shell exits.

  • If you want to detach from the shell and leave it running with the ability to re-attach, omit the --rm. You will then be able to reattach with: kubectl attach $pod-name -c $pod-container -i -t after you exit the shell.

  • If your shell does not start, check whether your cluster is out of resources (kubectl describe nodes). You can specify resource requests with --requests:

    --requests='': The resource requirement requests for this container.  For example, 'cpu=100m,memory=256Mi'.  Note that server side components may assign requests depending on the server configuration, such as limit ranges. 

(Credit: https://gc-taylor.com/blog/2016/10/31/fire-up-an-interactive-bash-pod-within-a-kubernetes-cluster)

like image 62
Dmitry Minkovsky Avatar answered Oct 16 '22 16:10

Dmitry Minkovsky


In order to have a Pod created instead of a Deployment and to have it removed by itself when you exit it, try this:

kubectl run curl-debug --rm -i --tty --restart=Never --image=radial/busyboxplus:curl -- /bin/sh 

The --restart=Never flag is what it says to create a Pod instead of a Deployment object

Also - This image is lightweight, downloads fast and is good for network debugging.

Hope that helps

like image 31
Urosh T. Avatar answered Oct 16 '22 18:10

Urosh T.