When creating a Docker image, you can specify commands that will be executed when the container starts using the CMD
and ENTRYPOINT
instructions in your Dockerfile. While they may seem similar, these two instructions serve different purposes and are used in distinct ways.
Introduction to CMD
The CMD
instruction is used to set a default command for a container. When you run a container without specifying a command, the command specified by CMD
will be executed. For example:
FROM ubuntu
CMD ["bash"]
In this case, when you run the container using docker run -it myimage
, it will start a new bash shell inside the container.
Introduction to ENTRYPOINT
The ENTRYPOINT
instruction is used to set an entry point for a container. An entry point is a command that will always be executed when the container starts, regardless of any other commands specified. For example:
FROM ubuntu
ENTRYPOINT ["/bin/ping"]
In this case, when you run the container using docker run -it myimage
, it will start pinging the default target.
Interaction between CMD and ENTRYPOINT
When both CMD
and ENTRYPOINT
are specified in a Dockerfile, they interact with each other. The CMD
instruction provides default arguments to the ENTRYPOINT
command. For example:
FROM ubuntu
ENTRYPOINT ["/bin/ping"]
CMD ["localhost"]
In this case, when you run the container using docker run -it myimage
, it will start pinging localhost. However, if you specify a different target, such as docker run -it myimage google.com
, it will ping google.com instead.
Overriding CMD with Docker Run
When running a container using docker run
, you can override the default command specified by CMD
by providing additional arguments. For example:
FROM ubuntu
CMD ["bash"]
Running the container using docker run -it myimage bash
will start a new bash shell, but if you run it using docker run -it myimage /bin/sh
, it will start a new sh shell instead.
Best Practices
Here are some best practices to keep in mind when using CMD
and ENTRYPOINT
:
- Use
CMD
to set default arguments for anENTRYPOINT
command. - Use
ENTRYPOINT
to set an entry point for a container that should always be executed. - Avoid overriding the default shell (e.g.,
/bin/sh
) with a customENTRYPOINT
. - Keep your Dockerfile instructions concise and easy to read.
By following these guidelines, you can effectively use CMD
and ENTRYPOINT
to create containers that are easy to manage and customize.