Difference between CMD and ENTRYPOINT
In a Dockerfile, both CMD and ENTRYPOINT instructions are used to define the command that should be run when a container is started. However, they serve different purposes and have different behaviors.
CMD
- Purpose: Specifies the default command to run when a container starts.
- Usage: It can provide default arguments for the
ENTRYPOINTinstruction, or it can be overridden by supplying arguments todocker run. - Syntax:
- Shell form:
CMD command param1 param2 - Exec form:
CMD ["executable", "param1", "param2"]
- Shell form:
Example:
Dockerfile with CMD:
FROM ubuntu:latest
CMD ["echo", "Hello, World!"]
When you build and run this Docker image, it will execute echo Hello, World!.
docker build -t my-echo-image .
docker run my-echo-image
Output:
Hello, World!
If you run the container with a different command, it will override the CMD instruction:
docker run my-echo-image echo "Hi there!"
Output:
Hi there!
ENTRYPOINT
- Purpose: Configures a container to run as an executable.
- Usage: It is not intended to be overridden; it sets the main command that will always be executed.
- Syntax:
- Shell form:
ENTRYPOINT command param1 param2 - Exec form:
ENTRYPOINT ["executable", "param1", "param2"]
- Shell form:
Example:
Dockerfile with ENTRYPOINT:
FROM ubuntu:latest
ENTRYPOINT ["echo"]
CMD ["Hello, World!"]
When you build and run this Docker image, it will execute echo Hello, World!.
docker build -t my-entrypoint-image .
docker run my-entrypoint-image
Output:
Hello, World!
If you provide additional arguments to docker run, they will be appended to the ENTRYPOINT instruction:
docker run my-entrypoint-image "Hi there!"
Output:
Hi there!
Combining CMD and ENTRYPOINT
When both ENTRYPOINT and CMD are used together, CMD provides default arguments to the ENTRYPOINT.
Dockerfile with both ENTRYPOINT and CMD:
FROM ubuntu:latest
ENTRYPOINT ["echo"]
CMD ["Hello, World!"]
This means that CMD arguments will be passed to the ENTRYPOINT command by default, but they can still be overridden:
docker run my-entrypoint-image
Output:
Hello, World!
Override the default CMD arguments:
docker run my-entrypoint-image "Hi there!"
Output:
Hi there!
Key Differences
-
Default Behavior:
CMD: Provides default command and/or parameters that can be overridden from the command line when running the container.ENTRYPOINT: Sets the command and parameters that are not overridden from the command line.
-
Override Capability:
CMD: Can be easily overridden by specifying a different command when running the container.ENTRYPOINT: The command itself is not easily overridden, but arguments can be appended.
-
Use Case:
CMD: Suitable for specifying the default command and parameters when there's a need to provide flexibility to override.ENTRYPOINT: Suitable for ensuring a specific command is always run, useful for containers that should always run the same executable (e.g., a web server).