Trusted answers to developer questions

What is the CMD command in Docker?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

The CMD command​ specifies the instruction that is to be executed when a Docker container starts.

For example:

FROM ubuntu:latest
CMD echo 'Hello world'

This CMD command is not really necessary for the container to work, as the echo command can be called in a RUN statement as well.

The main purpose of the CMD command is to launch the software required in a container. For example, the user may need to run an executable .exe file or a Bash terminal as soon as the container starts – t​he CMD command can be used to handle such requests.

1 of 3

Syntax

The CMD command we saw earlier followed the Shell syntax:

CMD executable parameter1 parameter2

However, it is better practice to use the JSON array format:

CMD ["executable", "parameter1", "parameter2"]

Multiple CMD commands

In principle, there should only be one CMD command in your Dockerfile. When CMD is used multiple times, only the last instance is executed.

Overriding CMD

A CMD command can be overridden by providing the executable and its parameters in the docker ​run command. For example:

docker run executable parameters

The command above will override any CMD in the Dockerfile.

Many developers confuse CMD with ENTRYPOINT. However, ​ENTRYPOINT cannot be overridden by docker run. Instead, whatever is specified in docker run will be appended to ENTRYPOINT – this is not the case with CMD.

RELATED TAGS

docker
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?