What is the Difference Between CMD and ENTRYPOINT in a Dockerfile?

When working with Dockerfiles, two instructions often confuse beginners and even intermediate users: CMD and ENTRYPOINT.

Both are used to specify what should run inside the container, but they behave differently and serve different purposes. In this blog, we’ll dive into the key differences, use cases, and how to choose between them effectively.


🔍 Understanding CMD

CMD provides default arguments for the ENTRYPOINT instruction or the container’s execution command if ENTRYPOINT is not set.

Syntax:

CMD ["executable","param1","param2"]
# or
CMD command param1 param2

Example:

FROM ubuntu
CMD ["echo", "Hello, World!"]

If you run this image with:

docker run myimage

It will print Hello, World!.

You can override CMD at runtime:

docker run myimage echo "Overridden!"

🔍 Understanding ENTRYPOINT

ENTRYPOINT sets the main command that will always run when the container starts. It’s useful when you want your container to behave like a standalone executable.

Syntax:

ENTRYPOINT ["executable", "param1", "param2"]
# or
ENTRYPOINT command param1 param2

Example:

FROM ubuntu
ENTRYPOINT ["echo", "Hello,"]

Now running:

docker run myimage World!

Outputs:

Hello, World!

Unlike CMD, you can’t override ENTRYPOINT unless you use the --entrypoint flag.


🤝 Using CMD and ENTRYPOINT Together

Often, you’ll use both—ENTRYPOINT to define the main command, and CMD to define default arguments:

FROM ubuntu
ENTRYPOINT ["echo"]
CMD ["Hello, Docker!"]

Now:

docker run myimage

Outputs:

Hello, Docker!

And this:

docker run myimage "Custom Message"

Outputs:

Custom Message

🧠 Key Differences

FeatureCMDENTRYPOINT
PurposeDefault command or parametersFixed command to run
OverrideEasily overridden at runtimeNot overridden unless using --entrypoint
FlexibilityGood for dynamic useGood for fixed behavior
Use WithOptional alone, or with ENTRYPOINTOften paired with CMD for parameters

✅ When to Use What?

  • Use CMD when:
    • You want to provide default arguments.
    • The container’s behavior is frequently overridden.
  • Use ENTRYPOINT when:
    • You want to enforce a specific executable.
    • Your container is meant to behave like a CLI tool.
  • Use both when:
    • You want a fixed command (ENTRYPOINT) with default parameters (CMD) that users can optionally override.

🔚 Conclusion

Understanding the difference between CMD and ENTRYPOINT is crucial for writing robust Dockerfiles. While they might seem similar at first glance, they serve distinct roles in defining how a container behaves.

Choose wisely depending on whether your container acts more like a tool, a service, or a flexible runtime environment.

Sharing Is Caring:

Leave a Comment