Instead of CMD, you can use ENTRYPOINT. While they serve a similar purpose, they are two very different directives. Every Docker container has a default ENTRYPOINT – /bin/sh -c. Anything you add to CMD is appended post-ENTRYPOINT and executed; for example, CMD [“nginx”, “-g”, “daemon off;”] will be generated as /bin/sh -c nginx -g daemon off;. If you use a custom ENTRYPOINT instead, the commands you use while launching the container will be appended after it. So, if you define ENTRYPOINT [“nginx”, “-g”] and use docker run nginx daemon off;, you will get a similar result.

To get a similar result without adding any CMD arguments while launching the container, you can also use ENTRYPOINT [“nginx”, “-g”, “daemon off;”].

Tip

Use ENTRYPOINT unless there is a need for a specific CMD requirement. Using ENTRYPOINT ensures that users cannot change the default behavior of your container, so it’s a more secure alternative.

Now, let’s look at RUN versus CMD.

Are RUN and CMD the same?

No, RUN and CMD are different and serve different purposes. While RUN is used to build the container and only modifies the filesystem while building it, CMD commands are only executed on the writable container layer after the container is running.

While there can be several RUN statements in a Dockerfile, each modifying the existing layer and generating the next, if a Dockerfile contains more than one CMD command, all but the last one are ignored.

The RUN directives are used to execute statements within the container filesystem to build and customize the container image, thus modifying the image layers. The idea of using a CMD command is to provide the default command(s) with the container image that will be executed at runtime. This only changes the writeable container filesystem. You can also override the commands by passing a custom command in the docker run statement.

Now, let’s go ahead and build our first container image.

Leave a Reply

Your email address will not be published. Required fields are marked *