/ docker

Docker entrypoint vs cmd

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.
Docker Docs

and also note:

If the user specifies arguments to docker run then they will override the default specified in CMD.
Docker Docs

and finally:

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.
Docker Docs

At the risk of literally pasting from the docs, the most useful examples for the CMD syntax are:

  1. CMD ["executable","param1","param2"] (exec form, this is the preferred form)
  2. CMD ["param1","param2"] (as default parameters to ENTRYPOINT)
  3. 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:

  1. Build: 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
    
  2. Run: docker run -d example

  3. Observe: docker ps

     CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
     c9413037def0        example             "top -b"            9 seconds ago       Up 8 seconds                            nostalgic_meninsky