loading...

Docker – The CMD instruction

How to change the time zone on Windows Server 2019

The CMD instruction is used to define the default action taken when containers are run from images built with their Dockerfile. While it is possible to include more than one CMD instruction in a Dockerfile, only the last one will be significant. Essentially, the final CMD instruction provides the default action for the image. This allows you to either override or use the CMD in the image used in the FROM instruction of your Dockerfile. Here is an example where a trivial Dockerfile does not contain a CMD instruction and relies on the one found in the ubuntu image used in the FROM instruction:

You can see from the output of the history command that the ubuntu image includes the CMD ["/bin/bash"] instruction. You will also see that our Dockerfile does not have its own CMD instruction. When we run the container, the default action is to run "/bin/bash".

There are three forms of the CMD instruction. The first is a shell form. The second is an exec form, which is the best practice form to use. And, the third is a special exec form that has exactly two parameters, and it is used in conjunction with the ENTRYPOINT instruction, which we will talk about in The ENTRYPOINT instruction section. Here is the syntax for the CMD instruction.

# CMD instruction syntax
CMD command param1 param2 (shell form)
CMD ["executable","param1","param2"] (exec form)
CMD ["param1","param2"] (as default parameters to ENTRYPOINT)

Here are a few CMD instruction examples for your enjoyment:

# CMD instruction examples
CMD ["/bin/bash"]
CMD while true; do echo 'DQS Expose Demo' | nc -l -p 80; done
CMD echo "How many words are in this echo command" | wc -
CMD tail -f /dev/null
CMD ["-latr", "/var/opt"]

Like the RUN instruction, the shell form of the CMD instruction will use the ["/bin/sh", "-c"] shell command (or ["cmd", "/S", "/C"] for Windows) by default unless it is overridden with a SHELL instruction. However, unlike the RUN instruction, the CMD instruction does not execute anything during the building of the image but instead is executed when containers built from the image are run. If the container image being built will not have a shell, then the exec form of the instruction can be used as it does not invoke a shell. The CMD instruction adds a zero-byte-sized layer to the image.

Comments are closed.

loading...