Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 111 ยท Dockerfiles

CMD and ENTRYPOINT

Learn how CMD and ENTRYPOINT differ, how they combine, why exec form matters, how to override them, and why PID 1 decides whether your container stops cleanly.

A Dockerfile describes how to build an image, but an image is only useful if something runs when you start a container from it. That "something" is set by two instructions: CMD and ENTRYPOINT. They look similar, they are often confused, and getting them wrong causes some of the most frustrating Docker problems: arguments that vanish, containers that take ten seconds to stop, and programs that never see Ctrl+C.

In this lesson you will learn what each instruction does, the difference between exec form and shell form, how the two instructions combine, how to override them at run time, and why the process Docker starts (PID 1) is special. If you are new to Dockerfiles, read Writing a Dockerfile first.

The two forms: exec and shell

Both instructions can be written in two ways. The difference is not cosmetic.

DOCKERFILE
# Exec form: a JSON array. Docker runs the program directly.
CMD ["echo", "hello"]

# Shell form: a plain string. Docker wraps it in /bin/sh -c.
CMD echo hello

You can see exactly what Docker stored by inspecting the image. Build this tiny file:

DOCKERFILE
FROM alpine:3.22
CMD ["echo", "hello from CMD"]
CONSOLE
$ docker build -t cmd-demo .
$ docker run --rm cmd-demo
hello from CMD
$ docker image inspect cmd-demo --format '{{json .Config.Cmd}} {{json .Config.Entrypoint}}'
["echo","hello from CMD"] null

The image stores Cmd as a list of arguments and has no entrypoint (null). Now write the same thing in shell form and inspect it:

DOCKERFILE
FROM alpine:3.22
ENV NAME=world
CMD echo "hello $NAME" && sleep 300
CONSOLE
$ docker image inspect cmd-shell --format '{{json .Config.Cmd}}'
["/bin/sh","-c","echo \"hello $NAME\" && sleep 300"]

Shell form is just exec form with /bin/sh -c put in front for you. That has three consequences:

  1. Variable expansion works. The shell expands $NAME before running echo. In exec form there is no shell, so $NAME is passed literally:
DOCKERFILE
FROM alpine:3.22
ENV NAME=world
CMD ["echo", "hello $NAME"]
CONSOLE
$ docker run --rm cmd-exec
hello $NAME

If you want expansion in exec form, call the shell yourself: CMD ["sh", "-c", "echo hello $NAME"] prints hello world.

  1. Your program is not PID 1. The shell is. This matters a lot for signals, as you will see below.
  2. The image needs /bin/sh. A scratch or distroless image has no shell, so shell form fails there.

Use exec form (a JSON array with double quotes) by default. Use shell form only when you really want shell features such as variable expansion, pipes or &&, and then consider putting them in a script instead.

A common mistake is single quotes in the array. JSON requires double quotes; with single quotes Docker cannot parse the array and silently treats the whole line as shell form. The result is a confusing failure:

CONSOLE
$ docker image inspect sq-demo --format '{{json .Config.Cmd}}'
["/bin/sh","-c","['echo','hi there']"]
$ docker run --rm sq-demo
/bin/sh: [echo,hi there]: not found

CMD: the default command

CMD sets the default command (or default arguments) for a container. It is easy to replace: anything you put after the image name in docker run takes its place.

CONSOLE
$ docker run --rm cmd-demo
hello from CMD
$ docker run --rm cmd-demo echo override
override
$ docker run --rm cmd-demo ls /etc/alpine-release
/etc/alpine-release

Because CMD is only a default, an image with just a CMD behaves like a normal program launcher: docker run image bash gives you a shell instead of the app. This is how general-purpose images such as alpine, python or node work. Their CMD is usually a shell or an interpreter prompt.

Two more rules to remember:

  • Only the last CMD counts. If a Dockerfile has two, the earlier one is ignored. Building a file with CMD ["echo","first"] followed by CMD ["echo","second"] and running it prints second.
  • CMD does not run at build time. It is metadata saved in the image. To run commands while building, use RUN (see FROM and RUN).

If the command does not exist, the container never starts:

CONSOLE
$ docker run --rm cmd-demo nosuchcmd
docker: Error response from daemon: failed to create task for container: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: error during container init: exec: "nosuchcmd": executable file not found in $PATH

Docker reports this as exit status 127 ("command not found").

ENTRYPOINT: the fixed program

ENTRYPOINT defines the program that always runs. Whatever you put after the image name in docker run is not a replacement; it is appended as arguments.

DOCKERFILE
FROM alpine:3.22
ENTRYPOINT ["ping", "-c", "2"]
CMD ["127.0.0.1"]
CONSOLE
$ docker run --rm ping-demo
PING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: seq=0 ttl=64 time=0.128 ms
64 bytes from 127.0.0.1: seq=1 ttl=64 time=0.105 ms

--- 127.0.0.1 ping statistics ---
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max = 0.105/0.116/0.128 ms

The container ran ping -c 2 127.0.0.1: the entrypoint, then the CMD as its arguments. Pass an argument at run time and it replaces the CMD part only:

CONSOLE
$ docker run --rm ping-demo localhost
PING localhost (::1): 56 data bytes
64 bytes from ::1: seq=0 ttl=64 time=11.968 ms
...

This is the pattern behind images that behave like command-line tools: docker run --rm my-image convert input.png feels like running the tool itself. The image is the program.

How CMD and ENTRYPOINT combine

When both exist, Docker runs ENTRYPOINT followed by CMD. CMD becomes the default arguments. Here is the full picture:

TEXT
                    no ENTRYPOINT          ENTRYPOINT ["a","b"]       ENTRYPOINT a b (shell)
no CMD              base image's CMD (if any) a b                        /bin/sh -c "a b"
CMD ["x","y"]       x y                     a b x y                    /bin/sh -c "a b"   (CMD ignored)
CMD x y (shell)     /bin/sh -c "x y"        a b /bin/sh -c "x y"       /bin/sh -c "a b"   (CMD ignored)

Two cells deserve a closer look because they surprise people.

Shell-form ENTRYPOINT ignores everything. With ENTRYPOINT echo "entrypoint:" and CMD ["ignored"], extra arguments never arrive, because the entrypoint is already a complete sh -c string:

CONSOLE
$ docker run --rm epshell extra args
entrypoint:

Shell-form CMD with an exec-form ENTRYPOINT produces nonsense. The CMD is turned into /bin/sh -c "echo hi" and passed as arguments to the entrypoint:

DOCKERFILE
FROM alpine:3.22
ENTRYPOINT ["echo", "args:"]
CMD echo hi
CONSOLE
$ docker run --rm combo
args: /bin/sh -c echo hi

The rule of thumb is simple: when you use ENTRYPOINT, write both instructions in exec form.

The combination rules apply at build time to what is saved in the image metadata. At run time, the arguments you type after the image name always replace CMD, never ENTRYPOINT.

Overriding the entrypoint

To replace the entrypoint itself, use --entrypoint. Note that it takes only the program; the arguments come after the image name.

CONSOLE
$ docker run --rm --entrypoint echo ping-demo replaced entrypoint
replaced entrypoint
$ docker run --rm --entrypoint "" ping-demo echo no entrypoint
no entrypoint

An empty --entrypoint "" clears it, so your arguments become the whole command. This is the standard trick for debugging an image whose entrypoint crashes: start a shell instead with docker run --rm -it --entrypoint sh image (see Debugging Containers).

Inheritance: what a child image keeps

Both settings are inherited through FROM. A child image with no CMD or ENTRYPOINT of its own keeps the parent's:

DOCKERFILE
FROM ping-demo
CONSOLE
$ docker run --rm ping-child
PING 127.0.0.1 (127.0.0.1): 56 data bytes
...

There is one subtle rule: setting ENTRYPOINT in a child image resets the inherited CMD. Docker assumes the old default arguments were meant for the old entrypoint.

DOCKERFILE
FROM ping-demo
ENTRYPOINT ["echo"]
CONSOLE
$ docker image inspect ping-child2 --format '{{json .Config.Entrypoint}} {{json .Config.Cmd}}'
["echo"] null
$ docker run --rm ping-child2

$

The container printed an empty line, because the inherited 127.0.0.1 argument was dropped. If you want a default argument, state a new CMD after the ENTRYPOINT.

The entrypoint script pattern

Many official images (PostgreSQL, MySQL, nginx) use a shell script as ENTRYPOINT to do setup work, then hand over to the real program given by CMD. The whole pattern fits in a few lines:

SH
#!/bin/sh
set -e
echo "[entrypoint] preparing, args: $*"
if [ "$1" = "serve" ]; then
  echo "[entrypoint] starting server mode"
fi
exec "$@"
DOCKERFILE
FROM alpine:3.22
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
CMD ["sh", "-c", "echo main process pid=$$"]
CONSOLE
$ docker run --rm script-demo
[entrypoint] preparing, args: sh -c echo main process pid=$$
main process pid=1
$ docker run --rm script-demo id -un
[entrypoint] preparing, args: id -un
root

Look at the last line of the script: exec "$@". It replaces the shell with the command it was given. That single word exec is the most important detail of the pattern, and the reason is PID 1.

PID 1 and signals

Inside a container, the first process (the one ENTRYPOINT/CMD starts) gets process ID 1 in the container's PID namespace. Linux treats PID 1 specially:

  • It receives the signals Docker sends. docker stop sends SIGTERM, waits a grace period (10 seconds by default), then sends SIGKILL.
  • A signal with no handler installed is ignored for PID 1, whereas for a normal process it would terminate it. This protects init on a real machine but surprises programs inside containers.
  • It is responsible for reaping orphaned child processes.

So what happens to a shell wrapper? Compare two wrappers around the same app. The app installs a SIGTERM handler and loops:

SH
#!/bin/sh
trap 'echo "app: got SIGTERM, cleaning up"; exit 0' TERM
echo "app: started as pid $$"
while true; do sleep 1; done

The first wrapper runs the app as a child. The second uses exec:

SH
# wrap-noexec.sh
#!/bin/sh
echo "wrapper: pid $$"
/app.sh

# wrap-exec.sh
#!/bin/sh
echo "wrapper: pid $$"
exec /app.sh

Starting each one and running docker stop -t 5 gives very different results:

CONSOLE
$ docker run -d --name t tcd /wrap-noexec.sh
$ docker stop -t 5 t
$ docker logs t
wrapper: pid 1
app: started as pid 6
$ docker inspect t --format '{{.State.ExitCode}}'
137

$ docker run -d --name t tcd /wrap-exec.sh
$ docker stop -t 5 t
$ docker logs t
wrapper: pid 1
app: started as pid 1
app: got SIGTERM, cleaning up
$ docker inspect t --format '{{.State.ExitCode}}'
0

Without exec, the shell is PID 1 and the app is its child (pid 6). The shell has no SIGTERM handler, so the signal is ignored, nothing is forwarded to the app, and after the grace period Docker kills the container with SIGKILL: exit code 137 (128 + 9) and no cleanup ever ran. With exec, the app becomes PID 1, receives the signal, cleans up and exits with code 0.

The same thing happens with a shell-form CMD. Both of these start sleep, yet only one makes it PID 1:

CONSOLE
$ docker exec shell-form ps -o pid,ppid,args
PID   PPID  COMMAND
    1     0 /bin/sh -c sleep 300; echo done
    7     1 sleep 300
$ docker exec exec-form ps -o pid,ppid,args
PID   PPID  COMMAND
    1     0 sleep 300

A container that "takes ten seconds to stop" almost always means the main program never saw SIGTERM: it sits behind a shell (shell-form CMD, a script without exec) or it never installed a handler. Fix it with exec form, exec in scripts, or an init process.

Using an init process

If your container starts several processes, or runs a program that does not handle signals or reap zombies, add a tiny init as PID 1 with docker run --init (or init: true in Compose). Docker injects docker-init, which forwards signals to your command and cleans up orphans:

CONSOLE
$ docker run -d --init --name t tcd /wrap-noexec.sh
$ docker exec t ps -o pid,ppid,args
PID   PPID  COMMAND
    1     0 /sbin/docker-init -- /wrap-noexec.sh
    6     1 {wrap-noexec.sh} /bin/sh /wrap-noexec.sh
    7     6 {app.sh} /bin/sh /app.sh
    9     7 sleep 1

The init is PID 1 and passes SIGTERM to the wrapper, so the stop is fast. But notice the wrapper still dies without telling the app (exit code 143, the signal was fatal to the shell). --init is a safety net; exec is the real cure. Signals, PID 1 and --init goes deeper.

When to use which

Situation Use
A normal application image CMD ["app", "--flag"] (exec form)
An image that behaves like one tool (a converter, linter, CLI) ENTRYPOINT ["tool"] plus CMD ["--help"] for defaults
Setup work before the real process (templating config, waiting, migrations) ENTRYPOINT ["entrypoint.sh"] that ends with exec "$@"
You need $VARIABLES, pipes or && A script (preferred) or shell form
Users should easily get a shell for debugging Prefer CMD over ENTRYPOINT; --entrypoint still works either way

Some professional habits:

  • Leave the command overridable. A CMD-only image lets anyone run docker run image sh for debugging without learning --entrypoint.
  • Keep entrypoint scripts tiny and always finish with exec "$@".
  • Do not use ENTRYPOINT just to hold the whole command if you plan to pass extra flags. If you ever need to run something else in the image, you will fight it.
  • Compose can override both: command: replaces CMD, entrypoint: replaces ENTRYPOINT. See Services in Compose.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A Dockerfile has ENTRYPOINT ["ping", "-c", "2"] and CMD ["127.0.0.1"]. What runs for docker run image localhost?

    Arguments after the image name replace CMD, but ENTRYPOINT always stays. The result is the entrypoint followed by your arguments.
  2. 2. Why does CMD ["echo", "hello $NAME"] print the text hello $NAME literally?

    Exec form starts the program directly with no shell in between. Use shell form or CMD ["sh", "-c", "..."] when you need expansion.
  3. 3. A script is the ENTRYPOINT and starts the real server on its last line without exec. What is the likely effect of docker stop?

    The shell script stays as PID 1 and has no SIGTERM handler, so the signal never reaches the server. After the timeout Docker sends SIGKILL. Ending the script with exec "$@" fixes this.
  4. 4. A parent image defines ENTRYPOINT and CMD. A child image adds only a new ENTRYPOINT. What happens to the inherited CMD?

    Setting ENTRYPOINT in a child image clears the inherited CMD, so the new entrypoint starts without the old default arguments.
  5. 5. How do you run a shell in an image whose ENTRYPOINT is set, to debug it?

    Plain arguments after the image name only replace CMD. The --entrypoint flag replaces the entrypoint itself.

Summary

  • CMD is the default command or default arguments; docker run image ... replaces it. Only the last CMD in a Dockerfile counts.
  • ENTRYPOINT is the program that always runs; arguments from docker run are appended to it. Replace it with --entrypoint.
  • Exec form (["prog", "arg"]) runs the program directly. Shell form wraps it in /bin/sh -c, which allows variables and pipes but puts the shell at PID 1.
  • When combining the two, write both in exec form. A shell-form ENTRYPOINT ignores CMD and run-time arguments.
  • A child image that sets ENTRYPOINT loses the inherited CMD.
  • PID 1 ignores signals it has no handler for. Use exec form and exec "$@" in entrypoint scripts so your program gets SIGTERM; add --init as a safety net.
  • Exit code 137 after docker stop usually means the process never saw the stop signal.

Next: ENV and ARG