DEV Community

Cover image for How to use Kubectl Exec Command?
CiCube Team for CICube

Posted on • Originally published at cicube.io

How to use Kubectl Exec Command?


cicube site


Introduction

Kubectl Exec is a command-line utility in Kubernetes that allows users to execute commands inside a container running in a pod. It provides direct access to containers, enabling users to troubleshoot, debug, and interact with applications deployed on Kubernetes clusters.

As Kubernetes orchestrates containerized applications, the ability to access and interact with individual containers becomes essential for tasks such as debugging, troubleshooting, and monitoring. Kubectl Exec facilitates this process by providing a seamless interface to execute commands within containers without the need for complex setups or additional tools.

This article aims to provide a comprehensive guide to the Kubectl Exec command, covering its basic usage, advanced features, security considerations, real-world applications, and troubleshooting strategies. By understanding and mastering Kubectl Exec, users can effectively manage and maintain their Kubernetes workloads with confidence.

What is Kubectl Exec?

Kubectl Exec is a command-line utility provided by Kubernetes, the popular container orchestration platform. It enables us to execute commands directly inside a container running in a pod within a Kubernetes cluster.

This functionality is useful for troubleshooting, debugging errors, test configuration changes, monitor application health, and interacting with applications deployed on Kubernetes.

Main Features

Direct Access: Kubectl Exec provides direct access to containers within pods, allowing users to run commands as if they were inside the container.

Multiple Containers: It supports pods with multiple containers, enabling users to choose which container to execute commands within.

Interactive Sessions: Users can initiate interactive sessions within containers, facilitating tasks such as debugging or running interactive scripts.

Standard I/O Streams: Kubectl Exec supports standard input, output, and error streams, making it easy to interact with containerized applications.

TTY Support: It provides TTY (teletypewriter) support for interactive sessions, allowing users to work with terminal-based applications inside containers.

Syntax

The syntax for using the kubectl exec command is:

kubectl exec [OPTIONS] POD_NAME -- COMMAND [args...]
Enter fullscreen mode Exit fullscreen mode

Parameters:

  1. POD_NAME: Indicates the name of the pod where the command is to be executed.
  2. [OPTIONS]: These are additional flags that can be supplied to kubectl exec for adjusting its functionality. For instance, the -it flag enables interactive mode for command execution.
  3. COMMAND: Specifies the command to be run inside the pod.
  4. args: Additional arguments provided to the command, if needed.

Before delving into accessing the container shell, let's begin by creating a Kubernetes deployment.

kubectl create deployment cicube-v2 --image=nginx
Enter fullscreen mode Exit fullscreen mode

If we wish to verify the deployment, we can use the command kubectl get deployments.

NAME        READY   UP-TO-DATE   AVAILABLE   AGE
cicube-v2   1/1     1            1           5m55s
Enter fullscreen mode Exit fullscreen mode

After creating the deployment, it's important to verify the Pod status to ensure proper functionality. You can do this by executing the following:

kubectl get pods
Enter fullscreen mode Exit fullscreen mode

Executing this command will show a list of all running Pods in your Kubernetes cluster. Locate the Pod with a name beginning with "cicube-v2" and confirm that it's in the "Running" state.

NAME                         READY   STATUS    RESTARTS   AGE
cicube-pod                   1/1     Running   0          20m
// highlight-next-line
cicube-v2                    1/1     Running   0          20m
nginx                        1/1     Running   0          22m
Enter fullscreen mode Exit fullscreen mode

When to ouse kubectl exec command?

Let's walk through a examples of using the kubectl exec command

Interactive sessions

Let's say we have a pod named cicube-v2 running a container with the nginx image, and we aim to execute a /bin/bash command within the container.

kubectl exec -it cicube-v2 -- /bin/bash
Enter fullscreen mode Exit fullscreen mode

This command launches a interactive shell session (bash) within the cicube-v2 pod, allowing you to execute multiple commands interactively.
To begin an interactive session within a container, you can use the -i (stdin) and -t (tty) flags:

kubectl exec interactive sessions

Now you can execute any command that you typically would using a shell.

Current date

This command will display the current date and time as reported by the container's operating system.

kubectl exec cicube-v2 -- date
Enter fullscreen mode Exit fullscreen mode
Wed Mar 27 12:36:28 UTC 2024
Enter fullscreen mode Exit fullscreen mode

Update container packages

To update container packages using kubectl exec, we can execute commands directly within the running container.

kubectl exec cicube-v2  -- apt-get update
Enter fullscreen mode Exit fullscreen mode

This command allows you to install or update packages as needed without accessing the underlying node or redeploying the container. It executes the apt-get update command within a container running inside the "cicube-v2" pod.

Image description

To list environment variables

We can list the environment variables in the running container with env command.

kubectl exec cicube-v2 -- env
Enter fullscreen mode Exit fullscreen mode

The output will look similar to the following:

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=cicube-v2
KUBERNETES_PORT=tcp://10.96.0.1:443
KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_PORT_443_TCP_PORT=443
KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
KUBERNETES_SERVICE_HOST=10.96.0.1
KUBERNETES_SERVICE_PORT=443
KUBERNETES_SERVICE_PORT_HTTPS=443
NGINX_VERSION=1.25.4
NJS_VERSION=0.8.3
PKG_RELEASE=1~bookworm
HOME=/root
Enter fullscreen mode Exit fullscreen mode

Passing environmet variables

We can pass environment variables to the command being executed within the pod using the --env flag.

kubectl exec -it cicube-v2 -- env MY_VAR=my_value /bin/bash
Enter fullscreen mode Exit fullscreen mode

Running commands as a specific User

We can run commands within pods as a specific user by using the --as flag.

kubectl exec -it cicube-v2 --as new-user -- /bin/bash

Enter fullscreen mode Exit fullscreen mode

Port Forwarding with kubectl exec

We can forward ports from a pod to your local machine using the --port and --address flags.

kubectl exec -it cicube-v2 -- port-forward --address 0.0.1.1 8080:81
Enter fullscreen mode Exit fullscreen mode

Multiple Container

If the pod has multiple containers, you can specify the container in which to execute the command using the -c or --container flag.

kubectl exec -it cicube-v2 -c second-container -- /bin/bash
Enter fullscreen mode Exit fullscreen mode

This command runs the /bin/bash command within the second-container container in the cicube-v2 pod.

Best practices to ensure secure usage of Kubectl exec

I wanted to touch base regarding some best practices for securely using kubectl exec in our Kubernetes environment. As we continue to manage our infrastructure, it's essential to ensure that we're following security guidelines to protect our systems and data.

Firstly, it's crucial to limit access to kubectl exec commands. We should only grant these permissions to trusted users who require access for specific tasks. By restricting access, we minimize the risk of unauthorized actions on sensitive pods and namespaces.

Additionally, enabling Role-Based Access Control (RBAC) is essential. RBAC allows us to define fine-grained permissions for exec operations, ensuring that users only have access to the resources they need. By assigning roles with limited scopes, we can prevent unintended actions and maintain a secure environment.

Another important aspect is authentication. We must authenticate users accessing kubectl exec using strong mechanisms such as Kubernetes native authentication or integration with identity providers like OIDC or LDAP. This helps verify the identity of users and prevents unauthorized access.

Furthermore, encryption is key to securing communications during exec sessions. By enabling Transport Layer Security (TLS) encryption for all channels, we can prevent data interception and ensure the confidentiality of our data.

I also want to emphasize the importance of audit logging. Enabling auditing allows us to track exec commands and monitor for any suspicious activities. Regularly reviewing audit logs helps us identify and address security issues proactively.

Lastly, applying Pod Security Policies (PSPs) is crucial. These policies help enforce security configurations such as restricting privileged access and blocking certain volumes, contributing to a more secure infrastructure.

Conclusion

We have covered the basics of Kubectl Exec, including its main features, syntax, and usage examples. By mastering Kubectl Exec, users can effectively troubleshoot, debug, and interact with applications running on Kubernetes clusters. Understanding the security best practices for using Kubectl Exec is essential to maintain a secure environment and protect sensitive data.

Top comments (0)