What's the kubectl equivalent of docker exec bash in Kubernetes?

Viewed 2063

I successfully deployed my Kubernetes app using kubectl apply -f deployment.yaml. When I try to hit the URL endpoint, I'm getting an nginx 404 Not Found error page.

My next step is to open a bash shell on the docker instance that is running my app. How do I do this in Kubernetes?

How do I ssh into the docker container running my app, or docker exec bash to an app I've deployed to Kubernetes?

If I were running in docker I would run docker ps to find the container ID and then run docker exec -t ### bash to open a shell on my container to look around to troubleshoot why something isn't working.

What is the equivalent way to do this in Kubernetes?

Searching for a solution

I searched and found this URL, which says how to get a shell on your app. The summary of that URL is:

kubectl apply -f https://k8s.io/examples/application/shell-demo.yaml
kubectl get pod shell-demo
kubectl exec --stdin --tty shell-demo -- /bin/bash

But when I tried the equivalent commands, I got an error see below:

kubectl get pods --namespace my-app-namespace
NAME                               READY   STATUS    RESTARTS   AGE
dpl-my-app-787bc5b7d-4ftkb         1/1     Running   0           2h

Then I tried:

kubectl exec --stdin --tty my-app-namespace -- /bin/bash
Error from server (NotFound): pods "my-app-namespace" not found
exit status 1

I figured this happened because I was trying to exec into the namespace not the pod, so I also tried with the dpl-my-app-... (see below) but got the same error.

kubectl exec --stdin --tty dpl-my-app-787bc5b7d-4ftkb -- /bin/bash
Error from server (NotFound): pods "dpl-my-app-787bc5b7d-4ftkb" not found
exit status 1

What is the command I need to get the pod instance so that kubectl exec will work?

1 Answers

As correctly stated by @David Maze:

Your kubectl get pods command has a --namespace option; you need to repeat this in the kubectl exec command. – David Maze 12 hours ago

If you've created your Deployment: dpl-my-app in a namespace: my-app-namespace you should also specify the --namespace/-n parameter in all of your commands.

A side note!

There is a tool to change namespaces, called: kubens


With a following command:

  • kubectl exec --stdin --tty my-app-namespace -- /bin/bash

You've correctly identified the issue that you are trying to exec into a namespace but not into a Pod

With a following command:

  • kubectl exec --stdin --tty dpl-my-app-787bc5b7d-4ftkb -- /bin/bash

You've tried to exec into a Pod named dpl-my-app-787bc5b7d-4ftkb but in a default namespace. Not in a namespace your Pod is residing.

To exec into your Pod in a specific namespace you should use following command:

  • kubectl exec --stdin --tty --namespace my-app-namespace dpl-my-app-787bc5b7d-4ftkb -- /bin/bash

Please notice the --namespace is before -- where the commands to the Pod should be placed (like -- /bin/bash).


Additional resources:

Related