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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With