Understanding Docker CMD
The CMD
directive in a Docker container specifies the default command and arguments that will be executed when the container starts. Unlike the ENTRYPOINT
, the CMD
can be easily overridden at runtime when the container is started.
The CMD
can be defined in three forms:
- Exec form:
CMD ["executable", "param1", "param2"]
- Shell form:
CMD command param1 param2
- As default parameters for ENTRYPOINT:
CMD ["param1", "param2"]
The exec form is the preferred way to define the CMD
as it provides more flexibility and control over the execution process. In the exec form, the executable and its arguments are specified as a JSON array, which allows for better handling of arguments that contain spaces or other special characters.
The shell form, on the other hand, is more convenient for simple cases where the command and its arguments can be specified as a single string. However, the shell form may not handle complex arguments as well as the exec form.
The third form, where the CMD
is used as default parameters for the ENTRYPOINT
, is useful when you want to provide a set of default arguments for the main executable specified in the ENTRYPOINT
.
Here's an example of a Dockerfile that sets the CMD
to the echo
command with the argument "Hello, Docker!":
FROM alpine:latest
CMD ["echo", "Hello, Docker!"]
In this example, when the container is started, the echo "Hello, Docker!"
command will be executed as the default command.
The CMD
directive can be overridden at runtime using the command argument when running the container with the docker run
command. This allows you to easily change the default command of the container without modifying the Dockerfile.
Understanding the CMD
directive is crucial for configuring the default execution process in your Docker containers and ensuring that your applications run as expected.