Oct 14th, ‘24/8 min read

kubectl exec: Commands, Examples, and Best Practices

Learn essential commands, examples, and best practices for using kubectl exec to troubleshoot and manage your Kubernetes applications.

kubectl exec: Commands, Examples, and Best Practices

The kubectl exec command is an essential tool for working with containers in your Kubernetes pods. This guide will help you understand how to use kubectl exec it effectively, from the basics to advanced techniques and best practices.

With this guide, you'll be able to troubleshoot problems and interact with your containers more easily.

1. Introduction to kubectl exec

kubectl exec is a powerful command-line tool that allows you to execute commands directly inside a container running in a Kubernetes pod.

It's particularly useful for debugging, troubleshooting, and performing administrative tasks within your containerized applications.

Kubernetes Monitoring with Prometheus and Grafana | Last9
A guide to help you implement Prometheus and Grafana in your Kubernetes cluster

What is kubectl exec?

kubectl exec is a subcommand of the Kubernetes command-line interface (CLI) tool, kubectl. It enables you to run commands or start an interactive shell session within a running container, providing direct access to the container's environment and file system.

The Role of kubectl exec in Kubernetes Clusters

In a Kubernetes cluster, kubectl exec serves as a bridge between the cluster's control plane and the individual containers running in pods.

It allows administrators and developers to interact with containers without needing to log into the nodes directly, maintaining the abstraction and security model of Kubernetes.

2. Understanding Kubernetes Pods

Before diving deeper into kubectl exec, it's crucial to understand what a Kubernetes pod is.

What Is a Kubernetes Pod?

A pod is the smallest deployable unit in a Kubernetes cluster. It represents a single instance of a running process in your cluster and can contain one or more containers.

Pods are the basic building blocks of Kubernetes workloads and are managed by higher-level controllers like Deployments or StatefulSets.

Adding Cluster Labels to Kubernetes Metrics | Last9
A definitive guide on adding cluster label to all Kubernetes metrics

Pod Lifecycle and kubectl exec

kubectl exec can only be used with running pods. Understanding the pod lifecycle is essential for the effective use of this command:

  1. Pending: The pod has been created but one or more containers are not yet running.
  2. Running: All containers in the pod are running. This is when kubectl exec can be used.
  3. Succeeded: All containers in the pod have terminated successfully.
  4. Failed: At least one container in the pod has terminated with failure.
  5. Unknown: The state of the pod cannot be determined.

3. kubectl exec vs kubectl run

It's important to distinguish between kubectl exec and kubectl run, as they serve different purposes in the Kubernetes ecosystem.

kubectl run

kubectl run is used to create and run a new pod with a container. It's typically used for quickly spinning up a new workload in your cluster.

Example:

kubectl run nginx --image=nginx

This command creates a new pod named "nginx" using the nginx container image.

kubectl exec

kubectl exec, on the other hand, is used to execute commands within an existing, running container. It doesn't create new pods or containers but allows you to interact with those already running.

Example:

kubectl exec -it nginx -- /bin/bash

This command opens an interactive bash shell in the nginx pod.

Using Kubectl Logs: Guide to Viewing Kubernetes Pod Logs | Last9
Learn how to effectively use kubectl logs to view and analyze Kubernetes pod logs. Master advanced techniques, troubleshoot issues, and optimize your K8s deployments.

4. Syntax and Basic Usage

The basic syntax for kubectl exec is as follows:

kubectl exec [POD_NAME] -- [COMMAND]

For interactive sessions, you can use the -it flags:

kubectl exec -it [POD_NAME] -- [COMMAND]

Flags and Options

  • -i or --stdin: Keep stdin open even if not attached.
  • -t or --tty: Allocate a pseudo-TTY.
  • -c or --container: Specify the container name (useful for pods with multiple containers).
  • -n or --namespace: Specify the namespace of the pod.

5. Common Use Cases and Examples

Let's explore some common use cases and examples of using kubectl exec.

Opening an Interactive Shell

To open an interactive shell in a pod, use the following command:

kubectl exec -it nginx -- /bin/bash

This command opens a bash shell in the nginx pod, allowing you to run shell commands interactively.

Executing a Single Command

To execute a single command without entering an interactive shell, use:

kubectl exec nginx -- ls /usr/share/nginx/html

This command lists the contents of the /usr/share/nginx/html directory in the nginx pod.

Working with Multiple Containers

If a pod has multiple containers, you can specify the container using the -c flag:

kubectl exec -it my-pod -c my-container -- /bin/bash

Running a Python Script

To run a Python script in a Kubernetes pod, use:

kubectl exec my-python-pod -- python /app/my_script.py

This command executes the Python script located at /app/my_script.py within the my-python-pod.

How to Monitor Ephemeral Storage Metrics in Kubernetes | Last9
Explore practical methods for monitoring ephemeral storage metrics in Kubernetes to ensure efficient resource management and improve overall performance.

6. Working with Namespaces

Namespaces in Kubernetes provide a way to divide cluster resources among multiple users or projects. When using kubectl exec, you may need to specify the namespace if the pod is not in the default namespace.

Specifying a Namespace

To specify the namespace, use the -n or --namespace flag:

kubectl exec -n my-namespace my-pod -- /bin/bash

Listing Pods Across Namespaces

To see pods across all namespaces:

kubectl get pods --all-namespaces

This can be helpful when you need to identify the correct pod and namespace for kubectl exec.

7. Authentication and Security

When using kubectl exec, it's important to consider authentication and security implications.

Using kubeconfig

kubectl uses the kubeconfig file for authentication. Ensure your kubeconfig is properly set up with the correct credentials:

kubectl config view

Role-Based Access Control (RBAC)

RBAC in Kubernetes controls access to resources. To use kubectl exec, you need the appropriate permissions:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: pod-exec
rules:
  - apiGroups: [""]
    resources: ["pods/exec"]
    verbs: ["create"]

TLS and Secure Communication

kubectl communicates with the Kubernetes API server using TLS. Ensure your cluster has proper TLS certificates configured:

kubectl config view --raw

Look for the certificate-authority-data, client-certificate-data, and client-key-data fields.

kube-state-metrics: Your Complete Guide to Simplifying Kubernetes Observability | Last9
This guide provides an in-depth look at its setup and usage, helping you monitor and manage your Kubernetes clusters more efficiently.

8. Advanced kubectl Commands

kubectl offers many advanced commands beyond exec. Here are a few that complement exec functionality:

kubectl apply

Use kubectl apply to create or update resources defined in YAML files:

kubectl apply -f my-deployment.yaml

kubectl logs

View container logs:

kubectl logs my-pod

kubectl port-forward

Forward local ports to a pod:

kubectl port-forward my-pod 8080:80

kubectl rollout

Manage deployments:

kubectl rollout status deployment/my-app

9. Kubernetes API and YAML

Understanding the Kubernetes API and YAML is crucial for advanced usage of kubectl.

API Versions

Different resources use different API versions. For example:

apiVersion: apps/v1
kind: Deployment

Metadata and Annotations

Metadata and annotations provide additional information about resources:

metadata:
  name: my-deployment
  annotations:
    kubernetes.io/change-cause: "Update for v2"

Creating Resources with YAML

Create resources using YAML files:

kubectl create -f my-resource.yaml

10. Performance and Resource Management

kubectl exec can be used to monitor and manage resource usage within containers.

Checking CPU Usage

kubectl exec my-pod -- top

Viewing Container Resource Limits

kubectl exec my-pod -- cat /etc/pod-info/cpu_limit

Autoscaling

While not directly related to exec, understanding autoscaling is important:

kubectl autoscale deployment my-app --min=2 --max=5 --cpu-percent=80

11. Automation and DevOps Integration

Integrating kubectl exec into your DevOps workflows can enhance automation and monitoring.

Scripting with kubectl exec

Create shell scripts that use kubectl exec for automated tasks:

#!/bin/bash
for pod in $(kubectl get pods -l app=my-app -o jsonpath='{.items[*].metadata.name}')
do
  kubectl exec $pod -- /scripts/health-check.sh
done

CI/CD Integration

Incorporate kubectl exec commands in your CI/CD pipelines for deployment verification and testing.

Monitoring and Alerting

Use kubectl exec in conjunction with monitoring tools to perform health checks and gather metrics.

OpenTelemetry vs. Traditional APM Tools: A Comparative Analysis | Last9
This article compares OpenTelemetry and traditional APM tools with their strengths, weaknesses, and ideal use cases to help you choose the right solution for your application performance monitoring needs.

12. Windows and Cross-platform Considerations

While Kubernetes is often associated with Linux, it's important to consider Windows and cross-platform scenarios.

Windows Containers

For Windows containers, use PowerShell instead of bash:

kubectl exec -it my-windows-pod -- powershell

Cross-platform Scripts

When writing scripts that use kubectl exec, consider the operating system of both the client and the container:

if [[ "$OSTYPE" == "msys" ]]; then
  kubectl exec my-pod -- cmd /c dir
else
  kubectl exec my-pod -- ls -l
fi

13. Best Practices and Troubleshooting

Best Practices

  • Use kubectl exec sparingly in production environments.
  • Prefer using kubectl logs it for debugging when possible.
  • Always specify the container name in pods with multiple containers.
  • Use read-only file systems in containers to prevent unintended modifications.
  • Implement proper RBAC policies to control access to kubectl exec.
  • Regularly update kubectl to ensure compatibility with your cluster version.

Troubleshooting

If you encounter issues kubectl exec, consider the following:

  • Ensure you have the necessary RBAC permissions.
  • Check if the container is running and healthy.
  • Verify network policies aren't blocking access.
  • Use the -v flag for verbose output to diagnose issues.
  • Check the Kubernetes API server logs for any authentication or authorization issues.

Conclusion:

Mastering kubectl exec equips you with the skills to debug, troubleshoot, and manage your Kubernetes workloads effectively. It's essential to use this powerful tool responsibly, particularly in production environments.

As you grow more comfortable with kubectl exec, it will become an invaluable asset in your Kubernetes toolkit, allowing you to maintain and optimize your containerized applications with greater ease and efficiency.

🤝
If you're still unsure about this topic, consider joining our community on Discord! We have a dedicated channel where you can share your specific use cases and connect with other developers.

FAQs

Q: How do I use exec commands?

A: Use the kubectl exec command followed by the pod name and the command you want to execute. For interactive sessions, add the -it flags.

Q: What is the use of kubectl exec?

A: kubectl exec is used for executing commands within running containers, debugging, and performing administrative tasks.

Q: How to execute commands in pods?

A: Use the syntax kubectl exec [POD_NAME] -- [COMMAND] to execute commands in pods.

Q: How to Enter Into a Docker Container's Shell?

A: While kubectl exec is for Kubernetes, the equivalent for Docker is docker exec -it [CONTAINER_ID] /bin/bash.

Q: How do I open a shell session inside a running Kubernetes pod using kubectl exec?

A: Use the command kubectl exec -it [POD_NAME] -- /bin/bash to open an interactive shell session.

Q: Can you provide examples of using kubectl exec to interact with containers in a Kubernetes pod?

A: Examples include:

  • Listing files: kubectl exec my-pod -- ls /app
  • Checking environment variables: kubectl exec my-pod -- env
  • Running a specific script: kubectl exec my-pod – python /app/script.py

Newsletter

Stay updated on the latest from Last9.

Authors

Anjali Udasi

Helping to make the tech a little less intimidating. I love breaking down complex concepts into easy-to-understand terms.

Handcrafted Related Posts