exec

Execute a command in a container

Execute a command in a container

Command

  1. $ kubectl exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...]

Example I

Current State

  1. $ kubectl get pods
  2. NAME READY STATUS RESTARTS AGE
  3. nginx-6db489d4b7-qkd5d 1/1 Running 0 20m

Command

  1. kubectl exec nginx-6db489d4b7-qkd5d -- date

Notice that date is the command that we are executing on the pod.

Output

  1. Mon Sep 21 03:38:53 UTC 2020

Example II

Current State

  1. $ kubectl get pods
  2. NAME READY STATUS RESTARTS AGE
  3. nginx-6db489d4b7-qkd5d 1/1 Running 0 20m

Command

  1. kubectl exec nginx-6db489d4b7-qkd5d -- ls

Notice that ls is the command that we are executing on the pod.

Output

  1. bin
  2. boot
  3. dev
  4. docker-entrypoint.d
  5. docker-entrypoint.sh
  6. etc
  7. home
  8. lib
  9. lib64
  10. media
  11. mnt
  12. opt
  13. proc
  14. root
  15. run
  16. sbin
  17. srv
  18. sys
  19. tmp
  20. usr
  21. var

Exec Shell

To get a Shell in a Container, use the -t -i options to get a tty and attach STDIN.

  1. kubectl exec -t -i nginx-78f5d695bd-czm8z bash
  1. root@nginx-78f5d695bd-czm8z:/# ls
  2. bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var

Specifying the Container

For Pods running multiple Containers, the Container should be specified with -c <container-name>.