I'm always forgetting what is the difference between Docker's entry point vs Docker cmd. Which one to use and when?
Tldr: "You can use the exec form of ENTRYPOINT to set fairly stable default commands and arguments and then use either form of CMD to set additional defaults that are more likely to be changed."
The CMD Syntax vs ENTRYPOINT
When and why would I use CMD?
The docs state:
The main purpose of a CMD is to provide defaults for an executing container. These defaults can include an executable, or they can omit the executable, in which case you must specify an ENTRYPOINT instruction as well.
and also note:
If the user specifies arguments to docker run then they will override the default specified in CMD.
If you would like your container to run the same executable every time, then you should consider using ENTRYPOINT in combination with CMD. See ENTRYPOINT.
At the risk of literally pasting from the docs, the most useful examples for the
CMD syntax are:
CMD ["executable","param1","param2"] (exec form, this is the preferred form)
CMD ["param1","param2"] (as default parameters to ENTRYPOINT)
CMD command param1 param2 (shell form)
Docker CMD example
As an example, I always like to quickly and easily keep a container running during developerment. I need a non-terminating command for this. Otherwise my container keeps existing. So I use the linux
top command in batch (
-b) mode to keep it running.
FROM ubuntu:18.04 RUN apt-get update CMD ["top", "-b"]
Then I build and run, and observe the container is running without existing:
docker build -t example .
Sending build context to Docker daemon 14.85kB Step 1/3 : FROM ubuntu:18.04 ---> 775349758637 Step 2/3 : RUN apt-get update && apt-get install build-essential python -y ---> Using cache ---> eb7f1a548908 Step 3/3 : CMD ["top", "-b"] ---> Using cache ---> e65c32b29c69 Successfully built e65c32b29c69 Successfully tagged example:latest
docker run -d example
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c9413037def0 example "top -b" 9 seconds ago Up 8 seconds nostalgic_meninsky
Subscribe to Karma Computing
Get the latest posts delivered right to your inbox