I’m working on a question that wants me to deploy a pod with the nginx
image. The pod should sleep for 5000 seconds.
The command can be specified like so:
command: ["sleep", "5000"]
or like so:
command:
- sleep
- "5000"
Why can’t the command be specified like so:
command:
- sh
- -c
- sleep "5000"
or like so:
command:
- sleep "5000"
In other words, I’m confused about two things:
- What does
sh -c
do? I understand that-c
is there to denote arguments, but isn’t thesleep
command run usingsh
? - When can the command and args be listed on the same line, and when do they have to be on separate lines? In this example, why doesn’t
sleep "5000"
work? Why dosleep
and"5000"
have to be on separate lines? Also, why are quotes around the number 5000 required?
2
Answers
The two ways of running the command:
Is exactly the same as:
In both cases, it is interpreted as a list. It’s two ways of expressing a list.
The command cannot be specified as
command: sleep "5000"
because this would be interpreted as a single argument"sleep 5000"
rather than as two separate argumentssleep
and5000
.Think of it as running this command in shell:
This would be run as a single command and the
5000
would not be interpreted as an argument. Whereas the expression:command: [sleep, 5000]
would be interpreted as:Thus being interpreted correctly as an argument of sleep.
For
sh -c
,sh
calls the programsh
(shell) as the interpreter and the-c
flag means to execute the following command as interpreted by this program.-c
is the flag that tells the shell to execute the command that follows it. So in this scenario, it would be redundant to usesh -c
, and I’m uncertain if that would even execute correctly.Note that
command
andargs
as in K8s object definitions or manifest are in-facetentrypoint
andcmd
fields as found in container image definitions. These are supposed to behave in a certain specific way. for eg: if you look at at how docker images are defined, you would findentrypoint
andcmd
as 2 highly used fields.supplying
command
and/orargs
in K8s object definition overridesentrypoint
andcmd
fields of the associated container.entrypoint
in docker image definitions for example is allowed either as a single string (sleep 5000
) or as a broken down array (["sleep", "500"]). either ways, it’s eventually broken down into an array of arguments (i.e.sleep 5000
becomes ["sleep", "5000"]).I suppose K8s tries to simplify this by letting you supply this only as an array.
this article is a good reference to understand how
entrypoint
andcmd
work in combination on container image definitions. The behavior feels a bit unnecessarily complicated and I cannot thank K8s contributors more for they simplified it to some extent at least.