Differences between CMD and ENTRYPOINT in Docker
This is a study note from a tutorial video in YouTube: https://www.youtube.com/watch?v=fqMOX6JJhGo&t=4723s
In Dockerfile, you can specify commands to execute like below:
Dockerfile:
FROM java:8
EXPOSE 8080
CMD ["java", "-jar", "/WeibotopHistorySpring.jar"]
The example has a command to execute a java program using JSON format. The first parameter "java" is an executable and the others are the parameters of "java" program.
However in some cases we may want to change the parameter of the executable during a docker run. For example, you have below simple Dockerfile:
FROM Ubuntu
EXPOSE 8080
CMD ["sleep", "5"]
When run above Dockerfile, it will run a container and sleep for 5 seconds. What if we want it to sleep 10 seconds instead? You can run a container with a sleep 10 command because the command appended in docker run command will replace the default command in Dockerfile.
docker run ubuntu-sleep sleep 10
However the "sleep" command in the end looks a bit redundant because we know this docker container is used to do sleep. We can remove the sleep instruction from the run command by using ENTRYPOINT.
FROM Ubuntu
EXPOSE 8080
ENTRYPOINT ["sleep"]
So now you can simply append parameter "10" at the end of run command to change the sleep interval.
docker run ubuntu-sleep 10
There is a problem with the above modification using ENTRYPOINT to replace CMD because if no time is specified in the docker run command. The container will have a exception error because it misses operand for sleep command in container. You can combine both CMD and ENTRYPOINT to solve this problem:
FROM Ubuntu
EXPOSE 8080
ENTRYPOINT ["sleep"]
CMD ["5"]
Conclustion:
ENTRYPOINT appends the input from the docker run command, while CMD replaces the default command in Dockerfile with the input from the docker run command.
References: https://www.youtube.com/watch?v=fqMOX6JJhGo&t=4723s
Comments
Post a Comment