Junior — Middle
What is the difference between CMD and RUN commands in a Dockerfile, and what is each of them used for?
sobes.tech AI
Answer from AI
In the Dockerfile:
-
CMD sets the default command that will be executed when the container starts. It can be overridden when running the container with
docker run. -
RUN executes a command during the image build. It is used for installing packages, configuring the environment, etc. Each RUN command creates a new layer in the image.
Example:
FROM ubuntu:20.04
RUN apt-get update && apt-get install -y curl # executed during build
CMD ["/bin/bash"] # default command when starting the container
Thus, RUN is for preparing the image, CMD is for setting the container's behavior upon startup.