
Attaching to a running Pod
If your pod is up and running, and you want to run some commands from within the context of that container image, you can attach an interactive session to it. You do this via the kubectl attach command. A Pod must be active for this command to work, so if you’re trying to figure out why a Pod didn’t start properly, this command probably won’t help.
Attaching to a Pod will connect stdin into your process, and take anything from stdout and stderr and present it on the screen, so it’s more like an interactive version of the kubectl logs -f command. Whatever you specified for the container will need to take stdin in order for this to be useful. You will also need to explicitly enable the TTY in order to connect to it. If you do not, you will frequently see the following as a first line of the output:
Unable to use a TTY - container flask did not allocate one
If you had created a deployment from the nodejs example earlier using the following command:
kubectl run nodejs --image=quay.io/kubernetes-for-developers/nodejs:latest —-port=3000
You could attach to this Pod using the following command:
kubectl attach deployment/express -i -t
This will return a warning message:
Unable to use a TTY - container flask did not allocate one
If you don't see a command prompt, try pressing enter.
And thereafter, when you interact with the service, you will see stdout streamed in the Terminal window.
This is most effective if your application prints its logs to stdout and you want to watch those logs while you interact with your code, for example by using a web browser. To use a web browser to interact with your running Pod, remember to use either the kubectl proxy or kubectl port-forward commands, typically from another Terminal window, to route access from your laptop to your Pod within the cluster.
In many cases, you will be better served by using the kubectl logs command that we described earlier with the -f option. The primary difference is if you have enabled your application to react to input from stdin and you ran it with stdin and a TTY defined, then you can interact with it directly by using the kubectl attach command.