What is the difference between CMD and ENTRYPOINT in a Dockerfile?

 

In a Dockerfile, both CMD and ENTRYPOINT are instructions used to specify the command that will be executed when a container based on that Docker image is started. However, they serve different purposes and have different behaviors:

  1. CMD:
    • CMD is used to provide default arguments for the command that is specified in the ENTRYPOINT instruction or to provide a default command to run when the container starts if there is no ENTRYPOINT instruction.
    • You can specify the CMD instruction in three different ways:
      1. Exec form (array syntax): CMD ["executable","param1","param2"]
      2. Shell form (string syntax): CMD command param1 param2
      3. Shell form (JSON array syntax): CMD ["command", "param1", "param2"]
    • If you specify multiple CMD instructions in a Dockerfile, only the last one will take effect.

Example using CMD:

Dockerfile
# Use a base image FROM ubuntu:latest # Set the default command to run when the container starts CMD ["echo", "Hello, World!"]
  1. ENTRYPOINT:
    • ENTRYPOINT is used to specify the command that will be executed when the container starts. It provides the fundamental command to run and does not allow overriding the command when starting the container unless you explicitly use docker run --entrypoint to override it.
    • You can also specify the ENTRYPOINT instruction in the same three ways as CMD.

Example using ENTRYPOINT:

Dockerfile
# Use a base image FROM ubuntu:latest # Set the entry point command ENTRYPOINT ["echo", "Hello, World!"]

Here are some important differences between CMD and ENTRYPOINT:

  • If you specify both CMD and ENTRYPOINT in a Dockerfile, the CMD values will be passed as arguments to the ENTRYPOINT command.
  • When you run a container, you can override the CMD values, but you cannot override the ENTRYPOINT command without using the --entrypoint option.
  • If you only specify CMD without ENTRYPOINT, the CMD instruction behaves like an executable, and you can override it entirely when starting the container.

For example, if you have a Dockerfile with CMD like this:

Dockerfile
CMD ["echo", "Hello, World!"]

You can override it when running the container:

bash
docker run my-image echo "Custom message"

In this case, the custom message will replace the default "Hello, World!" message specified in the CMD.

In summary, CMD is typically used for providing default arguments to the main command, whereas ENTRYPOINT is used to define the fundamental command to run, and it provides more control over the container's behavior.

Comments