Code Review Videos > Linux > How do I connect to a container in Kubernetes?

How do I connect to a container in Kubernetes?

This is for my future reference, covering how do I connect a running container in a Kubernetes pod?

First, it’s pretty useful to see all the pods in the namespace. Typically someone will have told me the right namespace to use, but if not, I can run:

kubectl get namespacesCode language: Shell Session (shell)

Which gives output like this:

NAME                                    STATUS   AGE
default                                  Active   3d
kube-system                       Active   3d
kube-public                         Active   3d
my-namespace                   Active   1d
another-namespace         Active   12h
...Code language: Shell Session (shell)

As with anything terminal based, it looks a bit nicer on the command line than it does pasted in to a WordPress blog post.

OK, so let’s pretend I am using my-namespace.

Next, I need to see all the pods in that namespace:

kubectl get pods -n my-namespaceCode language: Shell Session (shell)

Which gives output something like this:

NAME                              READY   STATUS    RESTARTS   AGE
my-app-pod-1               1/1          Running   0                     2m
my-app-pod-2               1/1          Running   0                     1m
my-database-pod        1/1          Running   0                      5m
...Code language: Shell Session (shell)

Usually the pods have names a little more ‘computery’ than that. Usually they had a hash ID as well, but again, pretty much good enough by way of example. I’ve had to massively anonymise the output here.

Now it’s pretty easy to get on the pod. Very Docker-esque, in fact.

kubectl exec -it -n my-namespace <pod-name> -- /bin/shCode language: Shell Session (shell)

Probably though, you have multiple containers in the pod (otherwise you probably don’t need K8s):

kubectl exec -it -n my-namespace <pod-name> -c <container-name> -- /bin/shCode language: HTML, XML (xml)

I think it’s also possible to somehow set the namespace so you don’t need it each time you run the command. Honestly, I find this stuff used fairly frequently (I’m far more dev than ops) so I mainly just grep lines like this out of my history.

But yeah, for future reference that is how I can connect to a running container in Kubernetes.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.