docker,

Dockerfile: RUN vs ENTRYPOINT vs CMD

Mar 02, 2023 · 2 mins read · Post a comment

We’ve all been trying our best to build the best possible, optimal Docker image out there. But, in order to do so, we need to understand and know the difference between one of most confound operations: RUN, ENTRYPOINT and CMD.

Prerequisites

  • Docker

Solution

RUN is used to execute a command during the build process to create or update an image. The result of the RUN command creates an intermediate image layer that is used to create the final image.

ENTRYPOINT is used to specify the command that should be run when the container is started. It is the default command that is executed when you start a container from an image, and it cannot be overwritten by docker run command arguments. ENTRYPOINT is often used to define the main application process that should run in the container.

CMD is used to provide default arguments to the ENTRYPOINT command or to specify a command to run if ENTRYPOINT is not defined. If ENTRYPOINT is not defined, then the CMD instruction will be the default command that is executed when you start a container from an image. If ENTRYPOINT is defined, then CMD provides the default arguments for that command.

Example to demonstrate the difference between ENTRYPOINT and CMD:

FROM alpine:latest

ENTRYPOINT ["echo", "test"]
CMD ["devcoops"]

In the example above, the ENTRYPOINT command is echo with the argument test. The CMD command is devcoops. When you run this container with docker run, it will output test devcoops.

However, if you run docker run myimage devops, the CMD command will be replaced with hi, so the output will be test devops.

Conclusion

In a nutshell, RUN is used during the build process, while ENTRYPOINT and CMD are used when running a container. ENTRYPOINT specifies the default command to run, and CMD provides default arguments to that command.

Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.