Skip to content
LF Cert Trainer

Lesson 48 · Section 5: Application Lifecycle Management

Lesson 48: Commands and arguments in Kubernetes: deciding what runs in a container

How the command and args fields of a container replace the image's ENTRYPOINT and CMD, who puts the final command line together, why there is no shell unless you ask for one, and the kubectl habits that get it right the first time. · 20 min read · 4 min video

1/10Commands and arguments
0:00 / 3:57

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why you need to change what a container runs

A container image is built once and then used in many places. The people who built it chose a program to start and some default arguments for it. Sooner or later those defaults do not fit:

  • The application should listen on another port, or read another configuration file.
  • You want more logging for an hour, and the switch for that is a command-line flag.
  • You need a throwaway Pod from a tools image that just stays alive, so that you can kubectl exec into it.
  • A Job should run a one-off script with the application's image, instead of the server.

It also matters for the cluster itself. On a kubeadm cluster, the API server, the scheduler and the controller manager are Pods, and every one of their settings is a flag in the command list of a manifest in /etc/kubernetes/manifests/. Changing how the control plane behaves means editing that list.

Rebuilding the image for each of these cases would be slow and would leave you with a pile of nearly identical images. Kubernetes gives every container two optional fields instead, command and args.

What command and args are

Two fields in the Pod replace two instructions in the imageImage (Dockerfile)Pod spec (container)replacesreplacesENTRYPOINTdefault programCMDdefault argumentscommandyour programargsyour arguments
Two fields in the Pod replace two instructions in the image. The image carries a default program (ENTRYPOINT) and default arguments (CMD). In the Pod, command replaces the first and args replaces the second. The names do not match, which is the main source of confusion.

Parts:

  • ENTRYPOINT (default program), in Image (Dockerfile)
  • CMD (default arguments), in Image (Dockerfile)
  • command (your program), in Pod spec (container)
  • args (your arguments), in Pod spec (container)

Connections:

  • command to ENTRYPOINT: replaces
  • args to CMD: replaces

The previous lesson covered the image side. As a reminder, here is a tiny image:

FROM busybox:1.37
ENTRYPOINT ["ping"]
CMD ["localhost"]

Run it with nothing else and the container executes ping localhost. Docker lets you replace the two parts when you start the container, and Kubernetes has a field for each:

Image (Dockerfile)Docker command lineKubernetes container fieldMeaning
ENTRYPOINTdocker run --entrypoint ...commandThe program to start
CMDWords after the image nameargsThe arguments given to that program

The names are the trap. The Kubernetes field called command is not the Dockerfile's CMD. It is the entrypoint. Say it to yourself once in the right order: command is the entrypoint, args is the CMD.

Both fields belong to a container, next to image, and both are lists of strings:

apiVersion: v1
kind: Pod
metadata:
  name: pinger
spec:
  containers:
    - name: main
      image: registry.example.com/tools/pinger:1.0
      command: ["ping"]
      args: ["-c", "3", "kubernetes.default"]

YAML has two ways to write a list, and they mean the same thing. Use whichever you find easier to read and to edit quickly:

command: ["ping"]
args: ["-c", "3", "kubernetes.default"]
command:
  - ping
args:
  - -c
  - "3"
  - kubernetes.default

The same two fields exist wherever a container is described: in the Pod template of a Deployment, DaemonSet, StatefulSet, Job or CronJob, and in initContainers.

How the two fields combine with the image

There are four combinations, and each has a fixed result. For the pinger image above (ENTRYPOINT ["ping"], CMD ["localhost"]):

command in the Podargs in the PodWhat runsWhy
not setnot setping localhostEverything comes from the image
not set["-c", "3", "example.com"]ping -c 3 example.comThe image's ENTRYPOINT stays, your args replace CMD
["sleep"]not setsleepYour command replaces ENTRYPOINT, and the image's CMD is ignored
["sleep"]["3600"]sleep 3600Nothing comes from the image

The third row is the one to remember. You might expect sleep localhost, the new program with the old arguments. Kubernetes does not do that, and for a good reason: the default arguments were written for the default program, and they would almost never make sense for a different one. The cost is that sleep here starts with no arguments at all and exits at once with sleep: missing operand.

Because the final command line is simply command followed by args, you are free to split it wherever you like. These three containers run exactly the same thing:

command: ["sleep", "3600"]
command: ["sleep"]
args: ["3600"]
# only for an image that has no ENTRYPOINT, such as busybox
args: ["sleep", "3600"]

The last form works because an image without an ENTRYPOINT uses the first word of CMD as the program. busybox is such an image (its CMD is ["sh"]), and that is why kubectl run box --image=busybox -- sleep 3600 works even though it only sets args.

A real image shows why the split matters. The official nginx image has ENTRYPOINT ["/docker-entrypoint.sh"], a script that prepares the configuration, and CMD ["nginx", "-g", "daemon off;"].

  • args: ["nginx-debug", "-g", "daemon off;"] keeps the preparation script and swaps the server for its debug build. This is what the image's authors intend.
  • command: ["nginx-debug", "-g", "daemon off;"] skips the preparation script altogether.

When you only want to change arguments, set args and leave command alone.

How it works: from the Pod spec to a process

Who builds the final command linereadsCRIdefaultsstartsPod speccommand, args, envkubeletexpands $(VAR)containerdfills gaps from imageImage configENTRYPOINT, CMDProcess, PID 1program + arguments
Who builds the final command line. The kubelet replaces $(VAR) references and hands command and args to the container runtime. The runtime fills in whatever you left out from the image, then starts one process. No shell is involved at any point.

Parts:

  • Pod spec (command, args, env)
  • kubelet (expands $(VAR))
  • containerd (fills gaps from image)
  • Image config (ENTRYPOINT, CMD)
  • Process, PID 1 (program + arguments)

Connections:

  • Pod spec to kubelet: reads
  • kubelet to containerd: CRI
  • Image config to containerd: defaults
  • containerd to Process, PID 1: starts

Nothing in the control plane looks at these fields. The API server stores them as they are, and the work happens on the node when the container is created:

  1. The kubelet reads the container from the Pod spec: command, args and the environment variables it has built from env and envFrom.
  2. The kubelet expands $(VAR) references in both lists, using those environment variables (more on this below).
  3. The kubelet calls the container runtime over the Container Runtime Interface and passes the two lists separately.
  4. The runtime fills the gaps from the image. If command is empty it takes the image's ENTRYPOINT, and only in that case, if args is empty too, the image's CMD. This is the rule behind the table above.
  5. The runtime starts one process with the resulting list: the first item is the program, the rest are its arguments, each item passed as one argument exactly as written. That process is PID 1 in the container, and the container lives for as long as it does.

Step 5 has a consequence that catches almost everyone once.

There is no shell

There is no shell unless you start oneno shellstartsrunscommand: [echo]args: [$HOME]Prints $HOMEnothing expanded itcommand: [sh, -c]args: [echo $HOME]shexpands, pipes, &&Prints /rootthe shell expanded it
There is no shell unless you start one. Kubernetes starts the program directly, so nothing interprets $HOME, pipes or &&. When you need those, make the shell your command and give it the whole line as one argument.

Parts:

  • command: [echo] (args: [$HOME])
  • Prints $HOME (nothing expanded it)
  • command: [sh, -c] (args: [echo $HOME])
  • sh (expands, pipes, &&)
  • Prints /root (the shell expanded it)

Connections:

  • command: [echo] to Prints $HOME: no shell
  • command: [sh, -c] to sh: starts
  • sh to Prints /root: runs

When you type a command in a terminal, a shell reads the line first. It splits it into words, replaces $HOME, expands *.log, and sets up pipes and redirections. Only then does it start a program.

Kubernetes starts the program directly, with the list you gave it. Nobody splits words and nobody interprets anything:

You writeWhat the program receivesResult
command: ["sleep 3600"]A program named sleep 3600, space includedThe container cannot start: executable file not found in $PATH
command: ["echo"], args: ["$HOME"]The five characters $HOMEPrints $HOME
command: ["ls", "/var/log/*.log"]A path with a literal *No such file or directory
command: ["echo", "hi", ">", "/tmp/out"]Three arguments: hi, >, /tmp/outPrints hi > /tmp/out, writes no file

When you want shell features, start a shell yourself and hand it the line as one string. sh -c means "run the next argument as a script":

command: ["sh", "-c"]
args: ["echo started on $HOSTNAME; while true; do date >> /tmp/out; sleep 5; done"]

For anything longer than one line, a YAML block makes it readable. The | keeps the line breaks, so the script looks the way it would in a file:

command: ["sh", "-c"]
args:
  - |
    echo "waiting for the database"
    until nc -z db 5432; do
      sleep 2
    done
    echo "database is up"

This only works if the image contains a shell. Minimal images, such as the ones the control plane components use, have none, and sh -c then fails with the same "executable file not found" error.

Under the hood · A shell as PID 1 and slow Pod deletion

When a Pod is deleted, the kubelet asks the runtime to send SIGTERM to PID 1 of each container, waits for the grace period (30 seconds by default) and then sends SIGKILL.

If PID 1 is sh -c "my-server --port 8080", the shell may stay around as the parent of your server. A shell does not pass SIGTERM on to its children, so the server never hears the polite request and is killed after the full 30 seconds. Every delete and every rolling update becomes slow, and the application never gets to shut down cleanly.

The fix is one word. exec replaces the shell with the program, which then becomes PID 1 itself:

command: ["sh", "-c"]
args: ["echo preparing; exec my-server --port 8080"]

Better still, when you do not need shell features, do not use a shell.

Variables in command and args: $(VAR)

Kubernetes has one substitution of its own. The text $(NAME), with parentheses, is replaced by the kubelet with the value of the container's environment variable NAME before the process starts. No shell is needed:

spec:
  containers:
    - name: main
      image: busybox:1.37
      env:
        - name: TARGET
          value: kubernetes.default
      command: ["ping"]
      args: ["-c", "3", "$(TARGET)"]

The variable can come from anywhere a container's environment can: a literal value, a ConfigMap or a Secret (the next lessons), or the Pod's own fields. That makes it the standard way to feed configuration into a command line.

You writeWho replaces itWhen
$(TARGET)The kubeletBefore the container starts, in command and args
$TARGET or ${TARGET}A shell, if you started one with sh -cWhile the script runs
$$(TARGET)NobodyThe escape: the program receives the text $(TARGET)

Two details are worth knowing:

  • If no variable with that name exists, the reference is left as it is. There is no error. The program receives the literal text $(TARGET), which usually shows up as a strange message in the logs.
  • Inside sh -c, the shell's own $(date) (command substitution) looks the same. It still works, because the kubelet finds no variable called date and leaves the text alone for the shell. It would only clash if an environment variable had exactly that name.

Using it

Example · A Pod that stays alive so you can work inside it

Task: create a Pod toolbox from the image busybox:1.37 that runs sleep 3600.

Let kubectl write the manifest. Everything after -- is the container's command line:

kubectl run toolbox --image=busybox:1.37 --dry-run=client -o yaml --command -- sleep 3600 > toolbox.yaml
apiVersion: v1
kind: Pod
metadata:
  labels:
    run: toolbox
  name: toolbox
spec:
  containers:
    - command:
        - sleep
        - "3600"
      image: busybox:1.37
      name: toolbox
  restartPolicy: Always
kubectl apply -f toolbox.yaml
kubectl get pod toolbox                     # Running
kubectl exec -it toolbox -- sh              # work inside it

Without --command, the same words would have gone into args. For busybox both work. If the task says "the container must run the command sleep 3600", use --command, so that the result does not depend on what the image's entrypoint happens to be.

Example · Change only the arguments of an application

Task: a Deployment web runs an image whose entrypoint is the server binary and whose default argument is --port=8080. Make it listen on 9090 with verbose logging, without touching the entrypoint.

Open the Deployment with kubectl edit deployment web and add args to the container, leaving command out:

    spec:
      containers:
        - name: web
          image: registry.example.com/shop/web:2.4
          args:
            - --port=9090
            - --log-level=debug

Save, and the Deployment starts a rolling update, because the Pod template changed:

kubectl rollout status deployment web
kubectl describe pod -l app=web | grep -A3 "Args:"
    Args:
      --port=9090
      --log-level=debug

Remember that args replaces the image's whole CMD. If the image's defaults were --port=8080 --workers=4 and you still want four workers, you have to repeat --workers=4 in your list.

Example · Fix a Pod with a wrong command

Task: the Pod report is in CrashLoopBackOff. Find out why and fix it.

kubectl describe pod report
    Command:
      sleep 600
    State:          Waiting
      Reason:       CrashLoopBackOff
    Last State:     Terminated
      Reason:       StartError
      Message:      ... exec: "sleep 600": executable file not found in $PATH

The program name is sleep 600, space included: somebody wrote command: ["sleep 600"]. The fix is command: ["sleep", "600"]. A running Pod's command cannot be changed, so kubectl edit pod report refuses the change when you save, and keeps your edited version in a temporary file:

error: pods "report" is invalid
A copy of your changes has been stored to "/tmp/kubectl-edit-1395347318.yaml"

Use that file to delete the Pod and create it again in one step:

kubectl replace --force -f /tmp/kubectl-edit-1395347318.yaml
kubectl get pod report                      # Running

If the Pod had belonged to a Deployment, you would edit the Deployment instead and let it replace the Pods.

Example · Add a flag to a control plane component

Task: enable an extra admission plugin on the API server of a kubeadm cluster.

The API server is a static Pod, and its whole configuration is one command list. Each flag is one list item, and the first item is the program:

# /etc/kubernetes/manifests/kube-apiserver.yaml (shortened)
spec:
  containers:
    - name: kube-apiserver
      image: registry.k8s.io/kube-apiserver:v1.34.0
      command:
        - kube-apiserver
        - --advertise-address=192.168.56.10
        - --authorization-mode=Node,RBAC
        - --enable-admission-plugins=NodeRestriction,NamespaceAutoProvision
        - --etcd-servers=https://127.0.0.1:2379

Edit the line with sudo vi, save, and the kubelet recreates the Pod by itself within a minute. A typo in a flag makes the API server exit at once, and then kubectl stops answering. In that case read the container's log on the node with sudo crictl ps -a and sudo crictl logs, or look in /var/log/pods/.

Tricks

Common mistakes

  • Mixing up the names. command is the image's ENTRYPOINT, not its CMD. If you put arguments in command, the first one is treated as the program to run.
  • Setting command and expecting the image's arguments to stay. command alone drops the image's CMD. Repeat the arguments you still need.
  • One string for the whole line. command: ["sleep 3600"] looks for a program with a space in its name. Write ["sleep", "3600"], or use ["sh", "-c", "sleep 3600"].
  • A plain string instead of a list. command: sleep 3600 is rejected, because the field must be a list.
  • Unquoted numbers and booleans. Every item must be a string: "3600", "true".
  • Shell syntax without a shell. $HOME, |, >, && and * only work inside sh -c "...".
  • $VAR where $(VAR) was meant. Kubernetes only replaces the form with parentheses, and silently leaves an unknown name as it is.
  • A command that finishes. command: ["echo", "hello"] prints and exits. In a plain Pod the container is restarted again and again, and the Pod ends up in CrashLoopBackOff even though nothing failed. A Pod needs a program that keeps running. Something that should run once belongs in a Job.
  • Editing a running Pod. command and args cannot be changed on a Pod. Recreate it with kubectl replace --force -f, or change the Deployment that owns it.
  • Forgetting the double dash. Without --, a flag meant for the container, such as the -c of sh -c, is read by kubectl itself, and the command fails or does something else. Always write -- before the container's words.

Recap

  • A container's command replaces the image's ENTRYPOINT, and args replaces its CMD.
  • Leave both out and the image decides. Set only args to keep the program and change its arguments. Set command and the image's CMD is dropped as well.
  • Both are lists of strings. The runtime starts the program directly, with no shell; use sh -c when you need one, and exec inside it for a server.
  • $(VAR) is replaced by the kubelet from the container's environment; $VAR is only understood by a shell.
  • kubectl run ... -- words fills args, --command -- words fills command, and kubectl replace --force -f recreates a Pod whose command has to change.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

2 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Repair three Deployments whose containers fail because command and args were written the wrong way.

    Fix · Level 2 · standard · target 15 min

  • Section capstone. One Deployment, five jobs: get it past a broken init container, feed it from a ConfigMap and a Secret, add probes, release a new version with no gap, and prepare it for autoscaling.

    Fix · Level 3 · challenge · target 30 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.