What is the difference between CMD and ENTRYPOINT in a Dockerfile?

前端 未结 16 1736
自闭症患者
自闭症患者 2020-11-21 22:31

In Dockerfiles there are two commands that look similar to me: CMD and ENTRYPOINT. But I guess that there is a (subtle?) difference between them -

16条回答
  •  时光说笑
    2020-11-21 23:26

    I run across this and at the beginning I found it really confusing to be honest and I think this confusion comes from using the word "CMD" because in fact what goes there acts as argument. So after digging a little bit I understood how it works. Basically:

    ENTRYPOINT --> what you specify here would be the command to be executed when you container starts. If you omit this definition docker will use /bin/sh -c bash to run your container.

    CMD --> these are the arguments appended to the ENTRYPOINT unless the user specifies some custom argument, i.e: docker run ubuntu in this case instead of appending what's specified on the image in the CMD section, docker will run ENTRYPOINT . In case ENTRYPOINT has not been specified, what goes here will be passed to /bin/sh -c acting in fact as the command to be executed when starting the container.

    As everything it's better to explain what's going on by examples. So let's say I create a simple docker image by using the following specification Dockerfile:

    From ubuntu
    ENTRYPOINT ["sleep"]
    

    Then I build it by running the following:

    docker build . -t testimg
    

    This will create a container that everytime you run it sleeps. So If I run it as following:

    docker run testimg
    

    I'll get the following:

    sleep: missing operand
    Try 'sleep --help' for more information.
    

    This happens because the entry point is the "sleep" command which needs an argument. So to fix this I'll just provide the amount to sleep:

    docker run testimg 5
    

    This will run correctly and as consequence the container will run, sleeps 5 seconds and exits. As we can see in this example docker just appended what goes after the image name to the entry point binary docker run testimg . What happens if we want to pass a default value (default argument) to the entry point? in this case we just need to specify it in the CMD section, for example:

    From ubuntu
    ENTRYPOINT ["sleep"]
    CMD ["10"]
    

    In this case if the user doesn't pass any argument the container will use the default value (10) and pass it to entry point sleep.

    Now let's use just CMD and omit ENTRYPOINT definition:

    FROM ubuntu
    CMD ["sleep", "5"]
    

    If we rebuild and run this image it will basically sleeps for 5 seconds.

    So in summary, you can use ENTRYPOINT in order to make your container acts as an executable. You can use CMD to provide default arguments to your entry point or to run a custom command when starting your container that can be overridden from outside by user.

提交回复
热议问题