Understanding Docker's ENTRYPOINT and CMD keywords

Docker ENTRYPOINT CMD Dockerfile

3 min read | by Jordi Prats

Docker is a popular tool for deploying and running applications in a containerized environment. One of the important features of Docker is the ability to define a command to be executed when a container is started. This command can be specified in the Dockerfile using two keyword: ENTRYPOINT and CMD.

The ENTRYPOINT keyword specifies the executable that will be run when the container starts. On the other hand, the CMD keyword provides default arguments for that executable. When a container is run from an image that specifies both ENTRYPOINT and CMD, the CMD keyword is passed as arguments to the ENTRYPOINT.

If you specify only a CMD keyword in your Dockerfile but not an ENTRYPOINT, it will default to /bin/sh -c. This means that the command specified in CMD will be executed in a shell environment.

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

In this case, the default ENTRYPOINT is /bin/sh -c, and the CMD specifies that the command echo Hello, World! which should be run when the container starts (if not otherwise specified at runtime): When you run a container from this image, you will see the message Hello, World! printed to the console.

If specify both ENTRYPOINT and CMD in your Dockerfile, ENTRYPOINT specifies the executable that will be run, and CMD provides default arguments to that executable. Here is an example:

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

In this case, the ENTRYPOINT keyword specifies that the "echo" command should be run when the container starts, meanwhile CMD provides the default argument "Hello, World!". When you run a container from this image without specifying any arguments, you will see the message Hello, World! printed to the console.

You can also override CMD when you start a container. For example, to run the container with a different argument:

docker run dockerimagename "Goodbye, World!"

Finally, it is possible to override the ENTRYPOINT when you start a container. This is less common, but can be useful in some cases. For example:

docker run --entrypoint /bin/ls dockerimagename

In this case, the container is started with the /bin/ls command instead of the default ENTRYPOINT.


Posted on 02/05/2023

Categories