ENTRYPOINT vs CMD
CMD (Command)
Purpose: Provides default arguments for the container.
Usage: Use
CMDwhen you want to provide default behavior but allow it to be overridden by arguments supplied when running the container (docker run).
Example 1: Default command with override
FROM ubuntu:latest CMD ["echo", "Hello, World!"]
If you run the container as
docker run <image>, it will printHello, World!.If you provide a different command, like
docker run <image> echo "Goodbye", it will override theCMD.
ENTRYPOINT
Purpose: Sets the main executable for the container that is not easily overridden.
Usage: Use
ENTRYPOINTwhen you want to enforce a specific command or script as the container's entry point. Additional arguments provided withdocker runare passed as arguments to theENTRYPOINT.
Example 2: Enforce entry point
FROM ubuntu:latest ENTRYPOINT ["echo"]
Running
docker run <image> Hello, World!will always useecho, so the result will beHello, World!.You cannot replace
echounless you use the--entrypointflag.
Combining ENTRYPOINT and CMD
Combine
ENTRYPOINTandCMDfor flexible and reusable images.ENTRYPOINT specifies the main command, and CMD provides default arguments that can be overridden.
Example 3: Flexible combination
FROM ubuntu:latest ENTRYPOINT ["echo"] CMD ["Hello, World!"]
Running
docker run <image>will printHello, World!.Running
docker run <image> Goodbyewill printGoodbye, overridingCMDbut notENTRYPOINT.
Key Differences
| Feature | CMD | ENTRYPOINT |
| Overridable | Yes (via docker run arguments). | No, unless --entrypoint is used. |
| Intended Purpose | Default behavior or arguments. | Main executable/script. |
| Flexibility | More flexible (easier to override). | More rigid (forces specific usage). |
When to Use Which?
Use CMD when you want to provide a default, flexible behavior that users can easily override.
Use ENTRYPOINT when you want to enforce a specific script or command while still allowing extra arguments.