If you are interested in finding out how kubectl exec
works, then I hope you will find this post useful. We will look into how the command works by examing the relevant code in kubectl, K8s API Server, Kubelet and the Container Runtime Interface (CRI) Docker API.
About This Command
Thekubectl exec
command is an invaluable tool for those of us who regularly work with containerized workloads on Kubernetes. It allows us to inspect and debug our applications, by executing commands inside our containers.
Let’s use kubectl
v1.15.0 to run an example:
The first exec
command runs a date
command inside my Nginx container. The second exec
command uses the -i
and -t
flags to get a shell to my Nginx container.
The CLI Code
Let’s repeat the command with increased log verbosity:
Notice that there are two HTTP requests:
- a
GET
request to fetch the pod - a
POST
request to theexec
subresource of the pod.
The server responds with a 101 Upgrade
response header indicating to the client that it has switched to the SPDY protocol.
The API Server Code
Let’s examine the API Server’s code to see how it registers the rest.ExecRest
handler to handle /exec
subresource requests. This handler is used to determine the node endpoint to exec
to.
One of the things that the API Server does when starting is to instruct its embedded GenericAPIServer
to install the ‘legacy’ API: