CMD vs ENTRYPOINT in Dockerfile: Key Differences and Usage
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.
| Aspect | CMD | ENTRYPOINT |
|---|---|---|
| Purpose | Sets default command and arguments | Sets fixed command to run |
| Override Behavior | Can be overridden by docker run arguments | Cannot be overridden, but arguments can be appended |
| Use Case | Default command with flexibility | Main executable for the container |
| Syntax Forms | Exec form or shell form | Exec form or shell form |
| Combining | Can provide default args to ENTRYPOINT | Works with CMD to accept default args |
| Effect on Container | Container runs CMD unless overridden | Container 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.
FROM alpine CMD ["echo", "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.
FROM alpine ENTRYPOINT ["echo"] CMD ["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.ENTRYPOINT for containers with a main executable and CMD for default arguments.ENTRYPOINT and CMD offers fixed commands with flexible defaults.CMD easily; ENTRYPOINT requires arguments to modify behavior.