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:
CMD
:CMD
is used to provide default arguments for the command that is specified in theENTRYPOINT
instruction or to provide a default command to run when the container starts if there is noENTRYPOINT
instruction.- You can specify the
CMD
instruction in three different ways:- Exec form (array syntax):
CMD ["executable","param1","param2"]
- Shell form (string syntax):
CMD command param1 param2
- Shell form (JSON array syntax):
CMD ["command", "param1", "param2"]
- Exec form (array syntax):
- 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!"]
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 usedocker run --entrypoint
to override it.- You can also specify the
ENTRYPOINT
instruction in the same three ways asCMD
.
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
andENTRYPOINT
in a Dockerfile, theCMD
values will be passed as arguments to theENTRYPOINT
command. - When you run a container, you can override the
CMD
values, but you cannot override theENTRYPOINT
command without using the--entrypoint
option. - If you only specify
CMD
withoutENTRYPOINT
, theCMD
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
Post a Comment