×
☰ See All Chapters

Docker CMD command

After docker image is created you will have to run image. You should define what should happen when you run your image. For example when you run your image it should start application servers, it should start Database services. Sometimes you may need to set environment specific settings before starting any services... so on. To execute your desired tasks when docker image is run you have to set your executable instructions from either CMD command or from ENTRYPOINT command. In this chapter you will learn CMD command. In the next chapter Docker ENTRYPOINT Command we study about ENTRYPOINT command.

To run you image you should execute below docker command.

docker run <imagename>

Now when you image is run if you want to start your spring boot application you may have to create your dockerfile as below:

FROM ubuntu:latest

RUN apt-get update && \

    apt-get install -y curl \

    wget \

    openjdk-8-jdk

ENV JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java

ARG JAR_FILE=target/*.jar

COPY ${JAR_FILE} app.jar

CMD ["java","-jar","/app.jar"]

When docker run command is executed it runs the command java –jar /app.jar command on Ubuntu terminal.

 Below is another simple example, we just echo a message to console when docker image is run.

FROM ubuntu:latest

CMD ["echo", "Hello World"]

docker-cmd-command-0
 

Instructions set from CMD command can be overridden by providing instructions to docker run command. If any parameters are provided in docker run command, all the CMD command parameters will be ignored.

docker-cmd-command-1
 

Docker CMD command syntax

The CMD command has three types of syntax, as shown below:

Shell Syntax

CMD <command>

Example:

CMD echo "Hello World"

JSON Array Syntax

CMD ["executablecommand", "argument1", " argument2", ...]

executablecommand : This is the executable command should be supported form the base image.

argument1, argument2…: Arguments for the executablecommand

Example:

CMD ["echo", "Hello World"]

JSON Array Syntax to set the default parameters to ENTRYPOINT instruction

The third type of syntax is similar to the previous type. However, this type is used for setting the default parameters to the ENTRYPOINT instruction. Please read Docker ENTRYPOINT command chapter from here.

CMD ["argument1", " argument2", ...]

Example:

FROM ubuntu:latest

CMD "Hello World"

ENTRYPOINT ["echo"]

docker-cmd-command-2
 

All Chapters
Author