In a Dockerfile, both RUN
and CMD
are instructions, but they serve very different purposes. Here’s a detailed breakdown of their differences:
1. Purpose
RUN
:- Used to execute commands at build time to build your Docker image.
- It typically installs software, updates packages, or configures the image.
- The result of a
RUN
command is stored in the image as a new layer.
CMD
:- Used to specify the default command that will run when a container starts.
- It doesn’t execute during the image build process.
- It defines the behavior of the container when no other command is provided at runtime.
2. Syntax
RUN
RUN <command>
Example:
RUN apt-get update && apt-get install -y curl
CMD
CMD ["executable", "param1", "param2"] # Preferred JSON array format
CMD command param1 param2 # Shell form
Example:
CMD ["python", "app.py"]
3. When They Execute
RUN
: Executes while building the Docker image. EachRUN
creates a new intermediate layer in the image.CMD
: Executes when the container starts, and only if no other command is specified when running the container.
4. Use Cases
RUN
:- Installing dependencies, tools, or configuring the environment.
- Example:
RUN apt-get update && apt-get install -y python3
- The installed Python will be included in the built image.
CMD
:- Setting the default command for the container to execute when it starts.
- Example:
CMD ["python3", "app.py"]
- When the container runs, it will automatically execute
python3 app.py
.
5. Overriding
RUN
:- Cannot be overridden. Once executed during image build, the changes are part of the image.
CMD
:- Can be overridden by providing a command at runtime:
docker run <image> custom-command
- Can be overridden by providing a command at runtime:
6. Example in a Dockerfile
# Base image
FROM python:3.9
# Install dependencies (RUN is executed during build)
RUN pip install flask
# Add application code
COPY app.py /app/app.py
# Default command (CMD is executed when container starts)
CMD ["python", "/app/app.py"]
- When building the image:
- The
RUN pip install flask
installs Flask in the image.
- The
- When running the container:
- The
CMD
starts the app by runningpython /app/app.py
.
- The
If you run:
docker run my-image python /app/another_script.py
The CMD
is overridden, and the container runs python /app/another_script.py
.
7. Common Misunderstanding: CMD vs ENTRYPOINT
While CMD
sets the default command, it can be overridden. For tasks where you don’t want the command to be overridden easily, you should use ENTRYPOINT
.
Let me know if you want a breakdown of ENTRYPOINT
as well!