Difference between RUN and CMD in docker file

I am confused when to use CMD vs RUN . For example, to execute bash / shell commands (for example, ls -la ) I always used CMD or is there a situation when I use RUN ? Trying to understand the best practices of these two similar Dockerfile directives.

+215
docker dockerfile
May 26 '16 at 13:11
source share
6 answers

RUN - image building step, the state of the container after the RUN command will be transferred to the docker image. A Dockerfile can have many RUN steps that overlap to create an image.

CMD is the command that the container runs by default when the inline image starts. A Dockerfile can contain only one CMD . CMD can be overridden when the container starts using docker run $image $other_command .

ENTRYPOINT is also closely associated with CMD and may change the way the image container starts.

+324
May 26 '16 at 13:25
source share

RUN - Runs commands while we create the docker image.

CMD - launch commands when launching the created docker image.

+78
Jul 17 '17 at 6:56
source share

I found this article very useful for understanding the differences between the two:

RUN - The RUN instruction allows you to install the application and packages for this are required. It executes any commands on top of the current image and creates a new layer, fixing the results. Often you will find several RUN instructions in the Docker file.

CMD - The CMD command allows you to set a default command that will be executed only when the container starts without specifying a command. If the Docker container is working with a command, the command will be ignored by default. If the Dockerfile has more than one CMD instruction, all but the last CMD instruction are ignored.

+56
Jan 01 '16 at 13:14
source share

RUN - install Python, now in your container python with its image caught fire
CMD - python hello.py, run your favorite script

+6
Feb 20 '18 at 12:10
source share

Note. Do not confuse RUN with CMD. RUN actually executes the command and captures the result; CMD does nothing during build, but indicates the intended command for the image.

from docker file link

https://docs.docker.com/engine/reference/builder/#cmd

+5
May 01 '17 at 9:59 a.m.
source share

RUN Command: The RUN command will basically execute the default command when we create the image. It will also commit image changes for the next step.

There may be more than 1 RUN command to assist in the process of creating a new image.

CMD Command: CMD commands simply set the default command for the new container. This will not be done during assembly.

If the docker file has more than 1 CMD command, all of them are ignored except the last one. Since this command will not do anything, it will simply set the default command.

+5
Oct 29 '18 at 10:15
source share



All Articles