0
0
DockerComparisonBeginner · 3 min read

CMD vs ENTRYPOINT in Dockerfile: Key Differences and Usage

In a Dockerfile, CMD sets the default command to run when a container starts but can be overridden by command line arguments. ENTRYPOINT defines a fixed command that always runs, optionally combined with CMD to provide default arguments.
⚖️

Quick Comparison

This table summarizes the main differences between CMD and ENTRYPOINT in Dockerfiles.

AspectCMDENTRYPOINT
PurposeSets default command and argumentsSets fixed command to run
Override BehaviorCan be overridden by docker run argumentsCannot be overridden, but arguments can be appended
Use CaseDefault command with flexibilityMain executable for the container
Syntax FormsExec form or shell formExec form or shell form
CombiningCan provide default args to ENTRYPOINTWorks with CMD to accept default args
Effect on ContainerContainer runs CMD unless overriddenContainer always runs ENTRYPOINT
⚖️

Key Differences

CMD in a Dockerfile specifies the default command and arguments that run when a container starts. However, this command can be replaced by providing a different command in docker run. This makes CMD flexible for containers that might need different commands at runtime.

ENTRYPOINT sets the main command that always runs when the container starts. It is not replaced by docker run arguments but instead appends those arguments to the ENTRYPOINT command. This makes ENTRYPOINT ideal for containers designed to run a specific executable or script.

When used together, ENTRYPOINT defines the fixed command, and CMD provides default arguments. This combination allows you to have a fixed executable with flexible default options that users can override.

⚖️

Code Comparison

Example Dockerfile using CMD to run a simple script with default arguments that can be overridden.

dockerfile
FROM alpine
CMD ["echo", "Hello from CMD"]
Output
Hello from CMD
↔️

ENTRYPOINT Equivalent

Example Dockerfile using ENTRYPOINT to run the same script but with a fixed command. Arguments passed to docker run will be appended.

dockerfile
FROM alpine
ENTRYPOINT ["echo"]
CMD ["Hello from ENTRYPOINT"]
Output
Hello from ENTRYPOINT
🎯

When to Use Which

Choose CMD when you want to provide a default command that users can easily override by specifying a different command at runtime.

Choose ENTRYPOINT when you want your container to always run a specific executable or script, optionally allowing users to pass additional arguments.

Use both together to fix the executable with ENTRYPOINT and provide default arguments with CMD for flexibility.

Key Takeaways

CMD sets a default command that can be overridden at runtime.
ENTRYPOINT sets a fixed command that always runs, with arguments appended.
Use ENTRYPOINT for containers with a main executable and CMD for default arguments.
Combining ENTRYPOINT and CMD offers fixed commands with flexible defaults.
Override CMD easily; ENTRYPOINT requires arguments to modify behavior.