What is the difference between CMD and ENTRYPOINT in a Dockerfile?
In Dockerfiles there are two commands that look similar to me: CMD
and ENTRYPOINT
. But I guess that there is a (subtle?) difference between them - otherwise it would not make any sense to have two commands for the very same thing.
The documentation states for CMD
-
The main purpose of a CMD is to provide defaults for an executing container.
and for ENTRYPOINT
:
An ENTRYPOINT helps you to configure a container that you can run as an executable.
So, what's the difference between those two commands?
Answers
Both CMD
and ENTRYPOINT
are used in Dockerfiles to define the command that will be executed when a container starts. However, there are key differences between them:
CMD:
- Default Command:
CMD
is used to specify the default command and/or arguments that will be executed when the container starts if no other command is provided at runtime. - Overridable: The command specified in
CMD
can be overridden by providing a command when running the container withdocker run
. - Multiple CMDs: If multiple
CMD
instructions are provided in a Dockerfile, only the last one will take effect.
Example:
CMD ["nginx", "-g", "daemon off;"]
ENTRYPOINT:
- Executable Command:
ENTRYPOINT
is used to specify the executable command that will run when the container starts. It's similar to specifying a binary or script to run. - Arguments: Any arguments provided to
docker run
will be passed as arguments to the command specified inENTRYPOINT
. - Combining with CMD: You can use
ENTRYPOINT
withCMD
to provide a default command and still allow it to be overridden. If both are specified,CMD
provides default arguments to the command specified inENTRYPOINT
. - Form of Use: It can be used in both exec form (
["executable", "param1", "param2"]
) and shell form (executable param1 param2
).
Example:
ENTRYPOINT ["nginx", "-g", "daemon off;"]
Differences:
CMD
is used to provide default arguments to the main command, whileENTRYPOINT
specifies the main command itself.CMD
can be overridden by providing a command when running the container, whileENTRYPOINT
cannot be overridden but can have its arguments appended.ENTRYPOINT
is often used for running the main application or script in the container, whileCMD
is used for specifying default options or arguments for the main command.
Combined Use:
You can combine ENTRYPOINT
and CMD
in a Dockerfile to create more flexible and reusable images. For example:
FROM ubuntu
# Set the default command
ENTRYPOINT ["nginx"]
# Provide default arguments to the command
CMD ["-g", "daemon off;"]
This Dockerfile would run nginx
by default with the provided arguments, but you could override the arguments by specifying a different command when running the container.