This blog will list and explain multiple differences among RUN, CMD, and ENTRYPOINT commands.
What is the Difference Between RUN, CMD, and ENTRYPOINT in a Dockerfile?
The RUN is used to execute the command instructions and create new image layers. The CMD is used for setting the commands and their parameters to be executed by default after the container is started. The ENTRYPOINT configures the command to execute when the container starts, similar to CMD from a functionality perspective.
Let’s check out the working of RUN, CMD, and ENTRYPOINT with the help of the below-provided instructions.
Initially, create a Dockerfile and paste the following code into it that contains the alpine base image and the RUN time instruction for Docker containers:
RUN ["echo", "My new image created"]
After that, run the docker build command to build the Docker image using the Dockerfile:
As you can see, the instructions that are provided inside the Dockerfile have been executed while building the image:
Next, check the list of existing images by running the following command:
As you can see, the particular image has been created successfully:
Now, add the CMD instructions in the existing Dockerfile that will be executed when the container starts:
RUN ["echo", "My new image created"]
CMD ["Hi Welcome to my LinuxHint World!!"]
After doing so, build the new Docker image by executing the provided command:
Now, use the docker run command to create a Docker container:
As you can see, the container has been created and the CMD instructions executed successfully:
To override the content of the CMD instructions, now build a container along with the new instructions by executing the following command:
World"
The output of the above-executed command shows that the CMD instructions have been overriding:
Now, add the ENTRYPOINT instructions in the previously created Dockerfile that will tell the entry point to the container:
COPY t_prg.html /usr/share/nginx/html/index.html
ENTRYPOINT ["nginx", "-g", "daemon off;"]
Then, build a new image by executing the below-mentioned command:
Next, run the docker images command to list all the existing images:
As you can see, the newly created image exists in the list:
Now, run the following command to generate a container with an image:
Lastly, list the content of the container by running the ls command:
That’s all! We have described and illustrated with examples some of the differences between RUN, CMD, and ENTRYPOINT.
Conclusion
In Docker, the RUN is utilized for executing the command instructions and creating new image layers. While the CMD is used for setting the commands and their parameters, the ENTRYPOINT configures the command to execute when the container starts. This blog illustrated some of the important differences among the RUN, CMD, and ENTRYPOINT.