Get a Shell to a Running Container

    You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:

    Getting a shell to a container

    In this exercise, you create a Pod that has one container. The container runs the nginx image. Here is the configuration file for the Pod:

    application/shell-demo.yaml

    Create the Pod:

    1. kubectl apply -f https://k8s.io/examples/application/shell-demo.yaml

    Verify that the container is running:

    1. kubectl get pod shell-demo
    1. kubectl exec --stdin --tty shell-demo -- /bin/bash

    Note: The double dash (--) separates the arguments you want to pass to the command from the kubectl arguments.

    In your shell, list the root directory:

    In your shell, experiment with other commands. Here are some examples:

    1. ls /
    2. cat /proc/mounts
    3. cat /proc/1/maps
    4. apt-get update
    5. apt-get install -y tcpdump
    6. tcpdump
    7. apt-get install -y lsof
    8. apt-get install -y procps
    9. ps aux
    10. ps aux | grep nginx

    Look again at the configuration file for your Pod. The Pod has an emptyDir volume, and the container mounts the volume at /usr/share/nginx/html.

    In your shell, create an index.html file in the /usr/share/nginx/html directory:

    1. echo 'Hello shell demo' > /usr/share/nginx/html/index.html
    1. # Run this in the shell inside your container
    2. apt-get update
    3. apt-get install curl

    The output shows the text that you wrote to the index.html file:

    When you are finished with your shell, enter exit.

    1. exit # To quit the shell in the container

    Running individual commands in a container

    In an ordinary command window, not your shell, list the environment variables in the running container:

    1. kubectl exec shell-demo env

    Experiment with running other commands. Here are some examples:

    1. kubectl exec shell-demo -- ps aux
    2. kubectl exec shell-demo -- ls /
    3. kubectl exec shell-demo -- cat /proc/1/mounts

    If a Pod has more than one container, use --container or -c to specify a container in the kubectl exec command. For example, suppose you have a Pod named my-pod, and the Pod has two containers named main-app and helper-app. The following command would open a shell to the main-app container.

    What’s next

    • Read about

    Last modified April 26, 2022 at 12:30 AM PST: Reorg the monitoring task section (#32823) (f26e8eff2)