How to log in with kubectl exec when multiple containers are running in a Kubernetes Pod
My name is Teraoka and I am an infrastructure engineer.
This time we will talk about Kubernetes.
As described in the URL below, we
will show you how to log in to any container by running kubectl exec on a Pod where multiple containers are running
https://kubernetes.io/ja/docs/tasks/debug-application-cluster/get-shell-running-container/
Start the Pod
First, let's launch a Pod according to the manifest below.
This is a simple method that uses a deployment controller to start a Pod running an Nginx container.
apiVersion: apps/v1 kind: Deployment metadata: name: example-web namespace: default spec: selector: matchLabels: app: example-web replicas: 1 template: metadata: labels: app: example-web spec: containers: - name: nginx image: nginx:latest imagePullPolicy: Always ports: - containerPort: 80
Reflect the manifest.
$ Kubectl apply -f deployment_example_web.yaml
Check if the Pod has started.
$ kubectl get pods NAME READY STATUS RESTARTS AGE example-web-59fccdb6d4-slrkv 1/1 Running 0 13s
You've stood up.
If you want to log in to a container running within this Pod, use
$ kubectl exec -it example-web-59fccdb6d4-slrkv bash root@example-web-59fccdb6d4-slrkv:/#
Then you can log in.
Next, let's edit the manifest file a little.
apiVersion: apps/v1 kind: Deployment metadata: name: example-web namespace: default spec: selector: matchLabels: app: example-web replicas: 1 template: metadata: labels: app: example-web spec: containers: - name: nginx image: nginx:latest imagePullPolicy: Always ports: - containerPort: 80 - name: php-fpm image: php:7.4-fpm imagePullPolicy: Always ports: - containerPort: 9000
A PHP-FPM container has also been added.
The command to reflect is the same as before, so I will omit it, but
when you start the Pod, the READY part becomes 2/2.
$ kubectl get pods NAME READY STATUS RESTARTS AGE example-web-85cd8dbd8d-24rx4 2/2 Running 0 69s
Let's run the same kubectl exec as before.
$ kubectl exec -it example-web-85cd8dbd8d-24rx4 bash Defaulting container name to nginx. Use 'kubectl describe pod/example-web-85cd8dbd8d-24rx4 -n default' to see all of the containers in this pod.
Some message was displayed.
This means "The default container name is nginx, so check all container information using kubectl describe."
In other words, if you want to log into a PHP-FPM container, the above command cannot be used.
You can log in using the --container option as shown below.
$ kubectl exec -it example-web-85cd8dbd8d-24rx4 --container php-fpm bash root@example-web-85cd8dbd8d-24rx4:/var/www/html#
I was able to log in!
summary
This may seem obvious, but I'll leave it as a memorandum.
Learn more about Kubernetes. . .