Middle
What is the difference between CMD and ENTRYPOINT in a Dockerfile?
sobes.tech AI
Answer from AI
CMD sets the default command that will be executed when the container starts if the user does not specify another command. It can be overridden at runtime. ENTRYPOINT also sets a command to run, but it is not as easily overridden; it more likely defines a base command to which arguments passed at runtime are appended. CMD is often used to provide default arguments for ENTRYPOINT.
Examples:
Dockerfile with CMD:
FROM ubuntu
CMD ["echo", "Hello from CMD"]
Run:
docker run <image>
# Output: Hello from CMD
docker run <image> echo "Hello from overridden CMD"
# Output: Hello from overridden CMD
Dockerfile with ENTRYPOINT:
FROM ubuntu
ENTRYPOINT ["echo"]
Run:
docker run <image>
# Output:
docker run <image> "Hello from ENTRYPOINT"
# Output: Hello from ENTRYPOINT
Dockerfile with ENTRYPOINT and CMD:
FROM ubuntu
ENTRYPOINT ["echo"]
CMD ["Default message"]
Run:
docker run <image>
# Output: Default message
docker run <image> "Custom message"
# Output: Custom message
Summary table:
| Feature | CMD | ENTRYPOINT |
|---|---|---|
| Purpose | Default command or arguments | Base command to execute |
| Override | Easily overridden at runtime | Not easily overridden, more often supplemented with arguments |
| Usage with ENTRYPOINT | Provides default arguments | Defines the command to which arguments from CMD or runtime are added |
| Formats | Executable form, Shell form | Executable form, Shell form |