Docker Tip #36: The Difference between RUN and CMD in a Dockerfile
RUN lets you run commands but CMD also lets you run a command, so which one should you use, and when?
While you can run commands with both instructions, they are very different.
RUN
happens at build time. When you build your Docker image, Docker will read
in your RUN
command and build it into your image as a separate image layer.
CMD
happens at run time. This will likely be calling some type of process,
such as nginx, bash or whatever process your Docker image runs. This does not
create a separate image layer.
Your Dockerfile
may have many RUN
instructions but will have at most one CMD
.
Which one should you use and when?
- Are you building dependencies into your image? Use
RUN
- Are you launching / running your Dockerized process? Use
CMD