Docker CMD and Entrypoint #
Running Docker containers results in the container running and then exiting immediately.
Containers are not meant to persist; they finish a task, and exit.
CMD #
Use CMD to specify commands for containers in the Dockerfile.
The structure is CMD <command> <parameter>, such as CMD sleep 5.
Alternatively, it can be stated in an array form like CMD ["<command>", "<parameter>"], such as CMD ["sleep", "5"].
For instance, in a Dockerfile:
FROM Ubuntu
CMD sleep 5
^ This approach is hard-coded in the Dockerfile.
Entrypoint #
ENTRYPOINT is an alternative to CMD.
It differs from CMD in that it only requires the passing of a parameter in the invocation of a Docker run.
So the Dockerfile might look something like:
FROM Ubuntu
ENTRYPOINT ["<command>"]
And the run command would look something like this, where the parameter is implicitly passed to the command:
docker run <docker app> <parameter>
Where if the command is sleep, the following might be a specification to sleep for a certain number of seconds:
docker run <docker app> 10
If there’s ENTRYPOINT in the Dockerfile, but no specification of a parameter with the run, this will lead to an error by default. To handle this, use both ENTRYPOINT and CMD in the Dockerfile. This provides a default parameter, which would be overriden by any explicitly provided parameter in the run invocation.
FROM Ubuntu
ENTRYPOINT ["<command>"]
CMD ["<parameter>"]