Skip to content

Dockerfile

Difference between RUN, CMD and ENTRYPOINT

Section titled “Difference between RUN, CMD and ENTRYPOINT”
  • RUN executes a command in a new layer and commits the result to a new image. It is the build-time instruction — installing packages, compiling, creating directories.
  • CMD sets the default command and/or parameters, which can be overridden from the command line when the container runs. It therefore takes effect only when the container is started without a command of its own. If a Dockerfile contains more than one CMD, all but the last are ignored.
  • ENTRYPOINT configures the container to run as an executable. It is similar to CMD, except that arguments given on the docker run command line are appended to it rather than replacing it.

Used together, ENTRYPOINT names the program and CMD supplies default arguments that a caller can override.

All three instructions can be written in shell form or exec form:

  • In shell form the instruction runs through a shell — /bin/sh -c <command> by default, which the SHELL instruction can change. Environment variables are expanded and the usual shell syntax works.
  • In exec form — ["executable", "param1", "param2"] — the executable is invoked directly. No shell is involved, so there is no variable expansion and no shell string processing. It is also the way to run a specific interpreter, such as bash, rather than sh.

RUN therefore has two forms:

  • RUN <command> (shell form)
  • RUN ["executable", "param1", "param2"] (exec form)

Exec form is the preferred form for ENTRYPOINT and CMD. The reason is signal handling: shell form starts the process as a child of /bin/sh -c, and that shell does not forward signals, so the application never sees the SIGTERM that docker stop sends and is killed outright when the timeout expires.

Use RUN to build the image, adding layers on top of the base image.

Prefer ENTRYPOINT over CMD when the image is an executable and a particular command must always run; add CMD alongside it to supply default arguments that the caller can override.

Choose CMD on its own when the image needs a default command or arguments that a caller is expected to replace.

  • Dockerfile reference — the authoritative list of instructions, with the exact override semantics for ENTRYPOINT and CMD.