Sub topic 7
Starting the app: CMD, ENTRYPOINT, and exec form
This chapter assumes you can write a basic Dockerfile with FROM, COPY, and RUN, and that you can build and run an image with docker build and docker run. It covers the instructions that decide what process starts when a container starts: CMD, ENTRYPOINT, and the two syntaxes (exec form and shell form) you can use to write them.
What a container actually runs
An image stores a filesystem and some metadata. One piece of that metadata is the command to run when a container starts from the image. Two instructions set it:
CMDsets the default command, or the default arguments.ENTRYPOINTsets the executable that always runs.
A container lives as long as its main process lives. Docker calls this process PID 1, because it is the first process inside the container's process namespace. When PID 1 exits, the container stops. This is why getting the start command right matters more than it first appears.
If you give neither instruction, the image inherits whatever its base image defined. If the base defines nothing either, docker run fails with an error unless you pass a command on the command line.
Exec form and shell form
Both instructions accept two syntaxes.
| Form | Syntax | How it runs |
|---|---|---|
| Exec form | `CMD ["node", "server.js"]` | Docker starts `node` directly as PID 1. No shell is involved. |
| Shell form | `CMD node server.js` | Docker runs `/bin/sh -c "node server.js"`. The shell is PID 1. |
Exec form is a JSON array. That means you must use double quotes. Single quotes make the array invalid JSON, and Docker then silently falls back to treating the line as shell form.
Why exec form is usually the right choice
In shell form, sh is PID 1 and your app is its child. This causes three problems.
- Signals do not reach your app.
docker stopsendsSIGTERMto PID 1. Many shells do not forward it to the child. Docker waits 10 seconds by default, then sendsSIGKILL. Your app never gets to shut down cleanly, and every stop takes 10 seconds. - A shell must exist in the image. Minimal images such as
gcr.io/distroless/statichave no/bin/sh. Shell form fails there. - Extra process. You carry a shell process for the lifetime of the container.
Exec form avoids all three. The trade-off is that there is no shell processing. Variables are not expanded, and operators like &&, |, and > are not interpreted.
FROM node:20-slim
ENV PORT=3000
# Exec form: "$PORT" is NOT expanded. node receives the literal text.
CMD ["node", "server.js", "--port", "$PORT"]If you need variable expansion or pipes, you have two options. The first is to ask for a shell explicitly and use exec so the app replaces the shell as PID 1:
FROM node:20-slim
ENV PORT=3000
CMD ["sh", "-c", "exec node server.js --port \"$PORT\""]The second is to read the variable inside your application, which is usually cleaner. Node reads process.env.PORT, for example.
CMD: the default that is easy to replace
CMD provides a default. Anything you put after the image name in docker run replaces it completely.
FROM python:3.12-slim
CMD ["python", "--version"]Build and try it:
docker build -t cmd-demo .
docker run --rm cmd-demo
docker run --rm cmd-demo python -c "print('hello')"The first run prints the Python version. The second run ignores the CMD and runs the command you typed. Only one CMD takes effect. If a Dockerfile has several, the last one wins.
CMD suits images where users may want to run different things, such as a language runtime image where someone might open a shell or run a script.
ENTRYPOINT: the fixed executable
ENTRYPOINT declares what the container is. Arguments after the image name in docker run are appended to it instead of replacing it.
FROM python:3.12-slim
ENTRYPOINT ["python", "-m", "http.server"]
CMD ["8000"]When ENTRYPOINT and CMD are both in exec form, Docker concatenates them. The CMD portion acts as default arguments.
| Command | What runs |
|---|---|
| `docker run img` | `python -m http.server 8000` |
| `docker run img 9000` | `python -m http.server 9000` |
| `docker run img --bind 127.0.0.1 9000` | `python -m http.server --bind 127.0.0.1 9000` |
The executable stays fixed. Only the arguments change. This makes the image behave like a command-line tool, which is a good fit for utilities and for apps with a stable binary such as the Go example in the multi-stage chapter.
To replace the entrypoint itself, use the --entrypoint flag. This is useful for debugging:
docker run --rm -it --entrypoint sh cmd-demoNote that --entrypoint takes only the executable. Arguments go after the image name.
How the two combine
The combination rules are worth knowing exactly, because shell form changes them.
| Row | No ENTRYPOINT | ENTRYPOINT exec form | ENTRYPOINT shell form |
|---|---|---|---|
| **No CMD** | Error: nothing to run | Runs the entrypoint alone | Runs `sh -c` entrypoint |
| **CMD exec form** | Runs the CMD | Entrypoint followed by CMD | Entrypoint only. CMD is ignored. |
| **CMD shell form** | Runs `sh -c` CMD | Entrypoint followed by `sh -c` CMD (rarely useful) | Entrypoint only. CMD is ignored. |
Two rules cover most of the table:
- Shell-form
ENTRYPOINTnever receivesCMDordocker runarguments. It is almost always a mistake. - Pair
ENTRYPOINTwithCMDonly in exec form, and useCMDonly for default arguments.
Entrypoint scripts
A common pattern is an entrypoint script that does setup, then hands control to the real process. For example, it might render a config file from environment variables.
#!/bin/sh
set -e
# Setup work goes here, for example writing a config file.
echo "Starting with PORT=${PORT:-3000}"
# Replace this shell with the command given as arguments.
exec "$@"FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
RUN chmod +x docker-entrypoint.sh
USER node
ENTRYPOINT ["./docker-entrypoint.sh"]
CMD ["node", "server.js"]The script ends with exec "$@". $@ expands to the CMD (or whatever you passed to docker run), and exec replaces the shell with that process. Without exec, the shell stays as PID 1 and you are back to the signal problem. The script must also have the execute bit set, which the chmod line takes care of. A missing execute bit gives a permission denied error at startup.
Because CMD still works here, docker run img node --inspect server.js and docker run img sh both pass through your setup first.
Putting it into the Node.js example
For the Node.js application from earlier chapters, the simple choice is exec-form CMD with no entrypoint:
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
EXPOSE 3000
USER node
CMD ["node", "server.js"]Calling node directly, rather than npm start, matters. npm start adds npm and a shell between Docker and your app, and the signal forwarding problem returns. Running node directly keeps your app as PID 1.
One more point on PID 1. The kernel treats PID 1 specially: it does not apply default signal actions to it. A process running as PID 1 only responds to SIGTERM if it installs a handler. A Node server that never handles SIGTERM can ignore docker stop even in exec form. Handle the signal in your code:
const http = require("http");
const server = http.createServer((req, res) => {
res.end("ok\n");
});
server.listen(3000);
process.on("SIGTERM", () => {
server.close(() => process.exit(0));
});Alternatively, run docker run --init, which puts a tiny init process at PID 1 to forward signals and reap zombie processes.
Choosing between them
Use these criteria:
- Use exec-form
CMDalone when the image runs one application and you want users to be able to replace the command freely. - Use exec-form
ENTRYPOINTplusCMDwhen the image behaves like a tool with a fixed executable and adjustable arguments. - Use an entrypoint script when startup needs setup work. End it with
exec "$@". - Use shell form only when you need shell features and accept the signal handling cost, or wrap with
sh -c "exec ..."as shown above.
Common errors
- Single quotes in exec form.
CMD ['node', 'server.js']is not valid JSON. Docker treats it as shell form and the command fails with a confusing message such as/bin/sh: [node,: not found. exec format error. The script has no shebang line, or the binary was built for a different CPU architecture.permission denied. The entrypoint script is not executable.executable file not found in $PATH. The first element of the array is not an installed program. In slim or distroless images, tools likecurlorshmay be missing.- Windows line endings. A script saved with CRLF endings fails with
no such file or directory, because the shebang points to/bin/sh\r. - Expecting
$VARto expand in exec form. It does not. Usesh -cor read the variable in the app.
You can check what an image will run with docker inspect:
docker inspect --format 'Entrypoint={{json .Config.Entrypoint}} Cmd={{json .Config.Cmd}}' myapp:1.0For shell form, the output shows ["/bin/sh","-c","node server.js"], which confirms the shell is involved.
Exercise
A Dockerfile ends with ENTRYPOINT ["python", "-m", "http.server"] and CMD ["8000"]. What command runs for docker run img 9000, and what would change if the entrypoint line were written as ENTRYPOINT python -m http.server in shell form?
Show answer
With exec form, python -m http.server 9000 runs, because 9000 replaces the CMD and is appended to the entrypoint. With the shell-form entrypoint, Docker runs /bin/sh -c "python -m http.server" and ignores both the CMD and the 9000 argument, so the server uses its default port. The shell is also PID 1, so docker stop may not deliver SIGTERM to Python.
Exercise
Your entrypoint script does setup and then ends with node server.js instead of exec node server.js. docker stop now takes 10 seconds. Why, and what is the fix?
Show answer
Without exec, the shell script remains PID 1 and node runs as its child. SIGTERM goes to the shell, which does not forward it, so Docker waits 10 seconds and sends SIGKILL. The fix is to end the script with exec "$@" (or exec node server.js) so node replaces the shell as PID 1.