Agentic AI with Java: Live Cohort
DockerDockerfile Fundamentals

RUN Vs CMD In Dockerfile

Understand the difference between commands that run while building an image and commands that run when a container starts.

RUN and CMD are two of the most important Dockerfile instructions, and beginners often confuse them.

The difference is simple:

InstructionWhen it runs
RUNDuring image build
CMDWhen a container starts

This timing difference changes everything.

RUN runs while building the image

Use RUN for setup steps that should become part of the image.

Examples:

RUN apt update
RUN apt install -y curl
RUN npm install
RUN mvn package

These commands run during docker build.

docker build -t my-app .

The result of a RUN command is saved into the image layer.

CMD runs when the container starts

Use CMD to define the default command for the container.

Examples:

CMD ["java", "-jar", "app.jar"]
CMD ["npm", "start"]
CMD ["python", "app.py"]

These commands do not run during docker build. They run later when you start a container:

docker run my-app

Simple example

Consider this Dockerfile:

FROM ubuntu
RUN echo "Image is being built"
CMD echo "Container is starting"

When you build the image:

docker build -t run-cmd-demo .

Docker executes the RUN line.

When you run the container:

docker run run-cmd-demo

Docker executes the CMD line.

Why not use RUN to start the app

This is a common mistake:

RUN java -jar app.jar

That tries to start the application while building the image. But the purpose of the build is to create the image, not to run the application permanently.

The correct approach is:

CMD ["java", "-jar", "app.jar"]

Now the application starts when the container starts.

Shell form and exec form

Docker supports two common forms.

Shell form:

CMD java -jar app.jar

Exec form:

CMD ["java", "-jar", "app.jar"]

For application startup, prefer exec form. It handles signals more cleanly and avoids some shell-related surprises.

Quick memory rule

Use this rule:

NeedUse
Install packagesRUN
Build codeRUN
Copy setup into imageRUN
Start the appCMD
Define default container commandCMD

RUN prepares the image. CMD starts the container. Keep that line clear and most Dockerfile mistakes disappear.

Written By: Shiva Srivastava

How is this guide?

Last updated on