Sub topic 6
Shell form versus exec form
This chapter assumes you can write a basic Dockerfile and run docker build and docker run. It covers the two ways to write RUN, CMD, and ENTRYPOINT, and the errors that come from mixing them up.
The two forms
Each of these three instructions accepts its command in one of two syntaxes.
- Shell form is a plain string:
CMD echo "hello". Docker runs it as/bin/sh -c "echo hello"on Linux. - Exec form is a JSON array of strings:
CMD ["echo", "hello"]. Docker runs the program directly, with no shell in between.
| Property | Shell form | Exec form |
|---|---|---|
| Syntax | `CMD echo hi` | `CMD ["echo", "hi"]` |
| Runs through a shell | Yes, `/bin/sh -c` | No |
| Expands `$VARIABLES` | Yes | No |
| Supports pipes, `&&`, redirects | Yes | No |
| Main process (PID 1) | The shell | Your program |
| Needs a shell in the image | Yes | No |
Variable expansion
A shell expands variables, and a direct program launch does not. This example uses shell form:
# Shell form: run through /bin/sh -c, so $HOME is expanded
CMD echo "home is $HOME"
# Exec form: no shell, so $HOME is printed literally
# CMD ["echo", "home is $HOME"]With the shell form, the container prints the real home directory. With the exec form, it prints the text home is $HOME. If you need expansion in exec form, call a shell yourself: CMD ["sh", "-c", "echo home is $HOME"].
Choosing a form for each instruction
For RUN, shell form is the usual choice. Build steps often chain commands, and chaining needs a shell:
FROM python:3.12-slim
RUN apt-get update && apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*Chaining several commands in one RUN also produces a single layer, which keeps cache behavior simple.
For CMD and ENTRYPOINT, prefer exec form. The reasons:
- The program becomes PID 1 and receives signals such as
SIGTERMfromdocker stopdirectly. In shell form,/bin/shis PID 1 and often does not pass signals on, so the container waits for the stop timeout and is then killed. ENTRYPOINTin shell form ignores anyCMDand any arguments given todocker run. Exec form is required for theENTRYPOINTplusCMDpattern covered in a later chapter.- Images with no shell, such as
scratchor distroless images, can only run exec form.
A common error
This Dockerfile looks correct but fails:
FROM alpine:3.20
ENTRYPOINT echo
CMD ["hello"]Because ENTRYPOINT is in shell form, Docker runs /bin/sh -c echo and drops the CMD arguments. The container prints an empty line instead of hello. Changing the first line to ENTRYPOINT ["echo"] fixes it.
How the forms differ at run time
Exercise
A Dockerfile contains CMD ["echo", "Path is $PATH"]. What does the container print, and how do you change the line so it prints the real value of PATH while keeping exec form?
Show answer
It prints Path is $PATH literally, because exec form runs echo without a shell, so nothing expands the variable. Wrap the command in a shell: CMD ["sh", "-c", "echo Path is $PATH"].