CMD

  • This only executes at runtime when we launch the container.
  • Runs the command inside the container when it is launched.
  • Very equivalent to the docker run <args> <command>. But more specifically in CMD we run the real time applications, Mongodb, redis,apache etc.
  • Any command which is passed to docker run WILL override the one mentioned in the CMD instruction in Dockerfile.
  • There can only be one CMD instruction per Dockerfile. Well we could have more than one, but only the last one will be effective.

Shell form

  • Commands are expressed the same way as shell commands.
  • In this form if commands are provided then they are prepended by “/bin/sh -c”

e.g.

if in Dockerfile its given as CMD echo "hello world" its taken as /bin/sh -c 'echo "hello world"'

  • Variables interpolation also works just like in shell

e.g. CMD echo $var1

Exec form

  • Recommended approach compared to shell form.
  • Here the arguments are passed as JSON array like style

["command", "arg1"]

Advantage being that the containers dont need to have a shell and also avoids string munging.

  • No shell features could be used and so no variable expansion and no special characters ( &&,   , > … )

RUN

  • Build time instruction.
  • Used to install softwares / packages into the image layers

ENTRYPOINT

  • Recommended approach than CMD
  • Cannot be overriden by the commands provided at run time using docker run <command>
  • Cool point being that, anything command that is specified in docker run becomes as an argument to the ENTRYPOINT instruction.

Example

Dockerfile and its contents


Build an image using the above Dockerfile


Check if image is created or not


Now when provided arguments like ‘hello there docker images !, its becomes as an argument to the ENTRYPOINT ["echo"] instruction and hence the output.


By this you can definitely understand that eventhough /bin/bash is a command, its taken as literally string argument and is NOT INTERPRETED AS COMMAND.


Real world example of ENTRYPOINT

Dockerfile details


Build an image


Images listing


Run container

Observe the arguments -D FORGROUND which becomes as arguments to the ENTRYPOINT command.

Make sure that you mentioned -p to map the port. This is a very frequent happening mistake.


Run container another variation