When writing a Dockerfile, two commonly used instructions are RUN and CMD. At first glance, they might seem similar—they both run commands—but their purposes are very different.
Understanding the difference between RUN and CMD is essential for building efficient, predictable Docker images.
✅ Quick Summary
| Instruction | Purpose | When It Executes |
|---|---|---|
RUN | Executes a command while building image | At build time |
CMD | Sets the default command for the container | At container runtime |
🏗️ What is RUN in Docker?
RUN is used to build your image by executing commands during the image creation process.
✅ Example:
FROM ubuntu:20.04
RUN apt-get update && apt-get install -y nginx
This command:
- Installs
nginxinside the image - Becomes a permanent part of the image layers
✅ Use RUN for setup tasks like installing packages, creating directories, or modifying files.
🚀 What is CMD in Docker?
CMD provides the default command that runs when you start a container from the image.
✅ Example:
FROM ubuntu:20.04
CMD ["echo", "Hello from container!"]
When you run the container:
docker run my-image
It will output:
Hello from container!
✅ Use CMD to define the default action—such as starting a server or script—when the container launches.
🧪 Combined Example: RUN vs CMD
FROM node:18
# Install dependencies during build
RUN npm install -g http-server
# Start the server by default
CMD ["http-server", "./public"]
RUNinstalls the HTTP server during image creationCMDstarts it when the container runs
🔄 Overriding CMD at Runtime
The CMD instruction can be overridden at runtime:
docker run my-image echo "Overridden!"
This replaces the default CMD with your own command.
🚫 RUN cannot be overridden—it only runs at build time.
🧠 Summary
| Feature | RUN | CMD |
|---|---|---|
| Executes during | Image build time | Container runtime |
| Used for | Installing packages, preparing files | Defining default execution command |
| Adds to image | Yes (creates a new image layer) | No |
| Can be overridden | ❌ No | ✅ Yes, via docker run |
| Executes every time container runs | ❌ No | ✅ Yes |
🏁 Final Thoughts
Use RUN to prepare your Docker image and CMD to define its default behavior at runtime. Think of RUN as baking ingredients into the image, while CMD tells it what to do when it’s ready to serve.
Mastering this difference is key to writing clean, efficient, and predictable Dockerfiles.