In Docker, both CMD
and ENTRYPOINT
are instructions used in a Dockerfile to define how a container should run an application. However, they serve slightly different purposes
CMD: This instruction specifies the default command to be executed when a container starts. It can be overridden by passing arguments to docker run
. If a Dockerfile has multiple CMD
instructions, only the last one will take effect. If a container is run without specifying a command, the command in the CMD
instruction will be executed.
Example:
CMD ["python", "app.py"]
- ENTRYPOINT: This instruction specifies the command to be executed when a container starts and also allows the container to be run as an executable. It’s often used to set the main command for the container. If a Dockerfile has multiple
ENTRYPOINT
instructions, only the last one will take effect. Arguments passed todocker run
will be appended to theENTRYPOINT
command.
Example:
ENTRYPOINT ["python", "app.py"]
Combining CMD and ENTRYPOINT:
You can use both CMD
and ENTRYPOINT
together in a Dockerfile. When used together, CMD
provides default arguments for the ENTRYPOINT
command.
Example:
ENTRYPOINT ["python"]
CMD ["app.py"]
In this case, running docker run <image>
will execute python app.py
by default unless a different command is specified when running the container.
To summarize, CMD
sets default arguments for the main command, while ENTRYPOINT
defines the main executable or command to run when the container starts. They can be used independently or together to specify how the container should behave when it starts.