Docker Building images Difference between ENTRYPOINT and CMD


There are two Dockerfile directives to specify what command to run by default in built images. If you only specify CMD then docker will run that command using the default ENTRYPOINT, which is /bin/sh -c. You can override either or both the entrypoint and/or the command when you start up the built image. If you specify both, then the ENTRYPOINT specifies the executable of your container process, and CMD will be supplied as the parameters of that executable.

For example if your Dockerfile contains

FROM ubuntu:16.04
CMD ["/bin/date"]

Then you are using the default ENTRYPOINT directive of /bin/sh -c, and running /bin/date with that default entrypoint. The command of your container process will be /bin/sh -c /bin/date. Once you run this image then it will by default print out the current date

$ docker build -t test .
$ docker run test
Tue Jul 19 10:37:43 UTC 2016

You can override CMD on the command line, in which case it will run the command you have specified.

$ docker run test /bin/hostname

If you specify an ENTRYPOINT directive, Docker will use that executable, and the CMD directive specifies the default parameter(s) of the command. So if your Dockerfile contains:

FROM ubuntu:16.04
ENTRYPOINT ["/bin/echo"]
CMD ["Hello"]

Then running it will produce

$ docker build -t test .
$ docker run test

You can provide different parameters if you want to, but they will all run /bin/echo

$ docker run test Hi

If you want to override the entrypoint listed in your Dockerfile (i.e. if you wish to run a different command than echo in this container), then you need to specify the --entrypoint parameter on the command line:

$ docker run --entrypoint=/bin/hostname test

Generally you use the ENTRYPOINT directive to point to your main application you want to run, and CMD to the default parameters.