Dockerfile - CMD


CMD 


The CMD instruction is used to provide a default executable or an entry point for an executing container. The executable provided in CMD instruction will launch automatically when the container is run.


Let’s see an example:


In this example we will try to launch python CLI when a container is started. For this to happen we need to make the following changes in the dockerfile.

FROM ubuntu:14.04
LABEL name="learning-ocean"
LABEL email="[email protected]"
ENV NAME Gaurav
ENV PASS password
RUN pwd > /tmp/1stpwd.txt
RUN cd /tmp
RUN pwd>/tmp/2ndpwd.txt
WORKDIR /tmp
RUN pwd>/tmp/3rdpwd.txt
RUN apt-get update && apt-get install -y openssh-server && apt-get install -y python
RUN useradd -d /home/gaurav -g root -G sudo -m -p $(echo "$PASS" | openssl passwd -1 -stdin) $NAME
RUN whoami>/tmp/1stwhoami.txt
USER $NAME
RUN whoami>/tmp/2ndwhoami.txt
RUN mkdir -p /tmp/project
ADD testproject.tar.gz /tmp/project
CMD ["python"]


build an image from dockerfile using below command

docker image build -t myubuntu:11 .


In the above Dockerfile we have added CMD instruction to launch python CLI which will be launched when we build this image and run the container.

[email protected]:~/dockerfiles$ docker container run -it myubuntu:11
Python 2.7.6 (default, Nov 13 2018, 12:45:42)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hi..")
Hi..
>>> print("Welcome to Learning-ocean.com")
Welcome to Learning-ocean.com
>>> exit()
[email protected]:~/dockerfiles$

In the above output, we can see that the python CLI is launched.


Note: There can be only one CMD instruction in the dockerfile. If more than one CMD instruction is listed the last one will take effect.


In the dockerfile below we have added two CMD instructions to launch python and shell.

FROM ubuntu:14.04
LABEL name="learning-ocean"
LABEL email="[email protected]"
ENV NAME Gaurav
ENV PASS password
RUN pwd > /tmp/1stpwd.txt
RUN cd /tmp
RUN pwd>/tmp/2ndpwd.txt
WORKDIR /tmp
RUN pwd>/tmp/3rdpwd.txt
RUN apt-get update && apt-get install -y openssh-server && apt-get install -y python
RUN useradd -d /home/gaurav -g root -G sudo -m -p $(echo "$PASS" | openssl passwd -1 -stdin) $NAME
RUN whoami>/tmp/1stwhoami.txt
USER $NAME
RUN whoami>/tmp/2ndwhoami.txt
RUN mkdir -p /tmp/project
ADD testproject.tar.gz /tmp/project
CMD ["python"]
CMD ["sh"]

Building the image from the above Dockerfile and running the container will launch the shell because only the CMD instruction gets executed.