Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between RUN and CMD in a Dockerfile

I'm confused about when should I use CMD vs RUN. For example, to execute bash/shell commands (i.e. ls -la) I would always use CMD or is there a situation where I would use RUN? Trying to understand the best practices about these two similar Dockerfile directives.

like image 235
TakeSoUp Avatar asked May 26 '16 13:05

TakeSoUp


People also ask

What does CMD in Dockerfile do?

When building a Dockerfile, the CMD instruction specifies the default program that will execute once the container runs. A quick point to note: CMD commands will only be utilized when command-line arguments are missing.

What does run in Dockerfile mean?

RUN lets you execute commands inside of your Docker image. These commands get executed once at build time and get written into your Docker image as a new layer. For example if you wanted to install a package or create a directory inside of your Docker image then RUN will be what you'll want to use.

Can we have two CMD in Dockerfile?

There can only be one CMD instruction in a Dockerfile. If you list more than one CMD then only the last CMD will take effect. If CMD is used to provide default arguments for the ENTRYPOINT instruction, both the CMD and ENTRYPOINT instructions should be specified with the JSON array format.

What is the difference between Docker run and start command?

Start will start any stopped containers. This includes freshly created containers. Run is a combination of create and start. It creates the container and starts it.


1 Answers

RUN is an image build step, the state of the container after a RUN command will be committed to the container image. A Dockerfile can have many RUN steps that layer on top of one another to build the image.

CMD is the command the container executes by default when you launch the built image. A Dockerfile will only use the final CMD defined. The CMD can be overridden when starting a container with docker run $image $other_command.

ENTRYPOINT is also closely related to CMD and can modify the way a container starts an image.

like image 198
Matt Avatar answered Sep 21 '22 22:09

Matt