DEV Community

Manuel Castellin
Manuel Castellin

Posted on • Edited on

ENTRYPOINT vs. CMD: The Dockerfile Dilemma

Since I started using Docker ages ago, I occasionally come across blog posts or videos telling in details how the two are different, but failing to explain how and when to use them

With enough experience...

you quickly realise that each instruction helps in different situations.

The best use for ENTRYPOINT is...

to set the image's main command. Are you running the image as though it was a command? Then ENTRYPOINT is the right choice. In addition to that, you can use CMD to provide additional command line arguments.

For example: you can package the dig command to run DNS queries with this Dockerfile:

FROM ubuntu:18.04

RUN apt-get update &&\
        apt-get install -qqy --no-install-recommends dnsutils

ENTRYPOINT ["dig"]

CMD ["--help"]
Enter fullscreen mode Exit fullscreen mode

Notice that I have provided --help as default command line parameter for the container, this way, if none is provided, we the container displays the help page. (Because you have to love your users, don't you? 🙂)

If you now build and tag your image as dig:latest, you can run DNS queries with ease from any operating system!

# On your Windows or MacOs

❯ docker run dig google.com

; <<>> DiG 9.11.3-1ubuntu1.13-Ubuntu <<>> google.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 7619
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;google.com.            IN  A

;; ANSWER SECTION:
google.com.     377 IN  A   172.217.23.142

;; Query time: 55 msec
;; SERVER: 192.168.65.1#53(192.168.65.1)
;; WHEN: Thu Sep 24 12:51:14 UTC 2020
;; MSG SIZE  rcvd: 44
Enter fullscreen mode Exit fullscreen mode

AWESOME! 🔥

Forget about ENTRYPOINT...

when your container's users are not already familiar with how the ENTRYPOINT works! It's easy to get fancy by adding magic tricks at container startup, but avoid hiding nasty logic at all costs!

Use CMD for...

everything else! When in doubt, I always use the plain and simple CMD. And if you're not sure what your container should do by default, just give your users a Shell to work with, as simple as that.

CMD ["bash"]
Enter fullscreen mode Exit fullscreen mode

What do you think?

I'm curious to know how you use ENTRYPOINT and CMD in your Dockerfiles!

Thanks for reading! And don't forget to follow me if you want to see more content like this!

Top comments (1)

Collapse
 
manishfoodtechs profile image
manish srivastava

Nice... You need clap