CMD and ENTRYPOINT

PrasannaPrasanna
3 min read
  • Scenario:

    • When you run the Docker run Ubuntu command, it runs an instance of Ubuntu image and exits immediately.

    • If you list all containers, including those that are stopped, you will see that the new container you ran is in an exited state.

  • Now, why is that?

    • Unlike virtual machines, containers are not meant to host an operating system. Containers are meant to run a specific task or process, such as to host an instance of a web server or application server or a database, or simply to carry out some computation or analysis.
  • Once the task is complete, the container exits. A container only lives as long as the process inside it is alive.

    • If the web service inside the container is stopped or crashes, the container exits.
  • If you look at the Docker file for popular Docker images, like NGINX, you will see an instruction called CMD, which stands for command, that defines the program that will be run within the container when it starts.

CMD

  • One option is to append a command to the Docker run command and that way, it overrides the default command specified within the image.

    • Say you want the image to always run the sleep command when it starts. You would then create your own image from the base Ubuntu image and specify a new command.

    • Untitled

Untitled

ENTRYPOINT:

  • The entry point instruction is like the command instruction, as in, you can specify the program that will be run when the container starts.

  • And whatever you specify on the command line, in this case, 10, will get appended to the entry point.

Untitled

  • In case of the CMD instruction, the command line parameters passed will get replaced entirely.

  • Whereas in case of entrypoint, the command line parameters will get appended.

Scenario:

  • what if I run the Ubuntu sleeper image command without appending the number of seconds?

  • Then, the command at start up will be just sleep and you get the error that the operand is missing.

Untitled

Scenario:

  • So how do you configure a default value for the command if one was not specified in the command line?

  • That's where you would use both ENTRYPOINT, as well as the CMD instruction.

  • In this case, the command instruction will be appended to the entry point instruction.

Untitled

  • if we provide some other value, it will over ride the given CMD value

    #docker run ubunt-server 16

      • here 5 will be replaced by 16

Scenario:

  • how to modify the ENTRYPOINT instruction during run

    • docker run —entrypoint=sleepx ubuntu-server 16

      • above command will relpace sleep command to sleepx

In short

  • The entry point is the command that is run at startup,

  • and the cmd is the default parameter passed to the command.

0
Subscribe to my newsletter

Read articles from Prasanna directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Prasanna
Prasanna