In Docker, the RUN and CMD instructions serve different purposes, primarily relating to when and how commands are executed within the container lifecycle.
RUN Instruction:
- Purpose: The
RUNcommand is used to build the image. It executes the specified command(s) and commits the result to the image, so the changes become part of the image layers.
Use Case: Commonly used for installing software, setting up files, or configuring the environment.
RUN apt-get update && apt-get install -y nginx
Here,
RUN installs nginx in the image. When the image is built, the installed software is included in the image.CMD Instruction:
- Purpose: The
CMDcommand provides default instructions for the container. It defines what should be executed when a container starts.
Use Case: Typically, used to specify the main application or command to run in the container.
CMD ["nginx", "-g", "daemon off;"]
Key Differences
- Layering:
RUNadds layers to the image (since it's for building), whileCMDdoes not. - Multiple Commands: You can use multiple
RUNinstructions to set up the image, but only oneCMD. If there are multipleCMDinstructions, only the last one takes effect. - Overriding: The
CMDcommand can be overridden when starting a container withdocker run, whereasRUNcannot.
RUN is used to execute commands during the build process of a Docker image, while CMD is used to specify the default command to run when a Docker container is started from the image.

Comments
Post a Comment