Dockerfile: What’s the Difference Between RUN and CMD?

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

InstructionPurposeWhen It Executes
RUNExecutes a command while building imageAt build time
CMDSets the default command for the containerAt 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 nginx inside 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"]
  • RUN installs the HTTP server during image creation
  • CMD starts 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

FeatureRUNCMD
Executes duringImage build timeContainer runtime
Used forInstalling packages, preparing filesDefining default execution command
Adds to imageYes (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.

Sharing Is Caring:

Leave a Comment