Difference between CMD, RUN, and ENTRYPOINT in Dockerfiles.

Docker is a popular platform for building, shipping, and running distributed applications. One of the key features of Docker is the ability to create custom images using a script called a Dockerfile. The Dockerfile is a set of instructions that specify how to build a Docker image and configure the containers that will be run from that image.

In this article, we will dive into the three key elements of a Dockerfile: CMD, RUN, and ENTRYPOINT. Understanding these commands is crucial to creating Docker images that are both efficient and easy to use.

CMD:

The CMD instruction sets the default command that will be executed when a container is run from the image. The CMD instruction can be specified in three forms:

  1. CMD ["executable", "param1", "param2", ...]: Executes the command as an exec process.
  2. CMD ["param1", "param2", ...]: Executes the default command specified by the image’s ENTRYPOINT, passing the parameters as arguments.
  3. CMD command param1 param2 ...: Executes the command using a shell (i.e. /bin/sh -c).

It is important to note that only the last CMD instruction in a Dockerfile will be used, and the command specified in CMD can be overridden when the container is run.

Example:

CMD ["nginx", "-g", "daemon off;"]

RUN:

The RUN instruction is used to execute shell commands during the build process. Each RUN instruction creates a new layer in the image. The results of the commands are saved in the image and will be executed every time a container is started from the image.

When using the RUN instruction, it is important to keep in mind that each RUN instruction will create a new layer in the image. This can lead to larger image sizes and longer build times. It is often more efficient to combine multiple commands into a single RUN instruction.

Example:

RUN apt-get update && apt-get install -y nginx

ENTRYPOINT:

The ENTRYPOINT instruction sets the default command that is executed when the container starts. It is used to configure a container as an executable. The ENTRYPOINT instruction can be specified in two forms:

  1. ENTRYPOINT ["executable", "param1", "param2", ...]: Executes the command as an exec process.
  2. ENTRYPOINT command param1 param2 ...: Executes the command using a shell (i.e. /bin/sh -c).

The ENTRYPOINT command cannot be overridden when the container is started, unlike the CMD command. This makes the ENTRYPOINT instruction ideal for specifying the default command that should be run when a container is started.

Example:

ENTRYPOINT ["nginx", "-g", "daemon off;"]

In conclusion, the CMD, RUN, and ENTRYPOINT instructions are essential to creating effective Docker images. Understanding the differences between these commands and when to use them is crucial to building images that are efficient, easy to use, and well-suited for your needs.

Leave a Reply