Introduction
In this lab, you will learn how to use the Kubernetes exec
command to execute commands inside a container running in a Kubernetes pod. You will start with simple examples and gradually progress to more complex scenarios.
In this lab, you will learn how to use the Kubernetes exec
command to execute commands inside a container running in a Kubernetes pod. You will start with simple examples and gradually progress to more complex scenarios.
In this step, you will learn how to execute a command in a container running in a pod.
Start by creating a deployment with one replica and an Nginx container:
kubectl create deployment nginx --image=nginx --replicas=1
Wait for the pod to become ready:
kubectl wait --for=condition=Ready pod -l app=nginx
Use the kubectl exec
command to execute a command inside the Nginx container:
kubectl exec nginx -v < pod_name > --
Replace <pod_name>
with the name of the pod created in step 1, and you can get the <pod_name>
with the kubectl get pod -l app=nginx
command.
In this step, you will learn how to execute a command in a specific container running in a pod with multiple containers.
Create a pod with two containers: Nginx and BusyBox:
cat << EOF | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: nginx-busybox
spec:
containers:
- name: nginx
image: nginx
- name: busybox
image: busybox
command:
- sleep
- "3600"
EOF
Wait for the pod to become ready:
kubectl wait --for=condition=Ready pod nginx-busybox
Use the kubectl exec
command to execute a command inside the BusyBox container:
kubectl exec nginx-busybox -c busybox -- ls /bin
In this step, you will learn how to execute a command with a tty in a container.
Use the kubectl exec
command with the -it
options to execute a command with a tty:
kubectl exec -it nginx-busybox -- /bin/sh
Once inside the container shell, run a command:
echo "Hello, world!"
Exit the container shell:
exit
In this step, you will learn how to execute a command with environment variables inside a container.
Create a deployment with one replica and an Nginx container with an environment variable:
kubectl run nginx-env --image=nginx --env="MY_VAR=my-value"
Wait for the pod to become ready:
kubectl wait --for=condition=Ready pod -l run=nginx-env
Use the kubectl exec
command to execute a command inside the Nginx container that outputs the environment variable:
kubectl exec nginx-env -- sh -c 'echo $MY_VAR'
Replace nginx-env with the name of the pod created in step 1.
Congratulations, you have successfully completed the Kubernetes exec command lab! In this lab, you learned how to use the kubectl exec
command to execute commands inside containers running in Kubernetes pods. You also learned how to execute commands in specific containers, execute commands with a tty, and execute commands with environment variables. These skills are essential for debugging issues in a Kubernetes cluster.