Home  Docker   Difference ...

Difference between CMD and ENTRYPOINT

In a Dockerfile, both CMD and ENTRYPOINT instructions are used to define the command that should be run when a container is started. However, they serve different purposes and have different behaviors.

CMD

Example:

Dockerfile with CMD:

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

When you build and run this Docker image, it will execute echo Hello, World!.

docker build -t my-echo-image .
docker run my-echo-image

Output:

Hello, World!

If you run the container with a different command, it will override the CMD instruction:

docker run my-echo-image echo "Hi there!"

Output:

Hi there!

ENTRYPOINT

Example:

Dockerfile with ENTRYPOINT:

FROM ubuntu:latest
ENTRYPOINT ["echo"]
CMD ["Hello, World!"]

When you build and run this Docker image, it will execute echo Hello, World!.

docker build -t my-entrypoint-image .
docker run my-entrypoint-image

Output:

Hello, World!

If you provide additional arguments to docker run, they will be appended to the ENTRYPOINT instruction:

docker run my-entrypoint-image "Hi there!"

Output:

Hi there!

Combining CMD and ENTRYPOINT

When both ENTRYPOINT and CMD are used together, CMD provides default arguments to the ENTRYPOINT.

Dockerfile with both ENTRYPOINT and CMD:

FROM ubuntu:latest
ENTRYPOINT ["echo"]
CMD ["Hello, World!"]

This means that CMD arguments will be passed to the ENTRYPOINT command by default, but they can still be overridden:

docker run my-entrypoint-image

Output:

Hello, World!

Override the default CMD arguments:

docker run my-entrypoint-image "Hi there!"

Output:

Hi there!

Key Differences

  1. Default Behavior:

    • CMD: Provides default command and/or parameters that can be overridden from the command line when running the container.
    • ENTRYPOINT: Sets the command and parameters that are not overridden from the command line.
  2. Override Capability:

    • CMD: Can be easily overridden by specifying a different command when running the container.
    • ENTRYPOINT: The command itself is not easily overridden, but arguments can be appended.
  3. Use Case:

    • CMD: Suitable for specifying the default command and parameters when there's a need to provide flexibility to override.
    • ENTRYPOINT: Suitable for ensuring a specific command is always run, useful for containers that should always run the same executable (e.g., a web server).
Published on: Jul 03, 2024, 01:12 AM  
 

Comments

Add your comment