What is the difference between the CMD and RUN instructions in a Dockerfile?

Prepare for the KCNA Certification Test. Study with flashcards, multiple-choice questions, and detailed explanations to enhance your understanding of Kubernetes Cloud Native concepts. Ace your exam!

Multiple Choice

What is the difference between the CMD and RUN instructions in a Dockerfile?

Explanation:
The difference you’re being tested on is build-time versus run-time behavior in a Dockerfile. The RUN instruction is executed while the image is being built; its purpose is to install packages, set up the filesystem, or make other changes that are baked into the image. Each RUN adds a new layer and the results of that command become part of the image that you later run as a container. The CMD instruction, on the other hand, defines what should run when a container starts from that image. It’s a runtime default, not something that runs during image creation. You can override it by passing a command to docker run, and if you have an ENTRYPOINT, CMD provides default arguments to that entrypoint. So, the best way to distinguish them is: RUN builds and configures the image; CMD specifies the command to execute when the container starts. The other descriptions misstate the roles—RUN is not for runtime, CMD isn’t deprecated, and they aren’t interchangeable.

The difference you’re being tested on is build-time versus run-time behavior in a Dockerfile. The RUN instruction is executed while the image is being built; its purpose is to install packages, set up the filesystem, or make other changes that are baked into the image. Each RUN adds a new layer and the results of that command become part of the image that you later run as a container.

The CMD instruction, on the other hand, defines what should run when a container starts from that image. It’s a runtime default, not something that runs during image creation. You can override it by passing a command to docker run, and if you have an ENTRYPOINT, CMD provides default arguments to that entrypoint.

So, the best way to distinguish them is: RUN builds and configures the image; CMD specifies the command to execute when the container starts. The other descriptions misstate the roles—RUN is not for runtime, CMD isn’t deprecated, and they aren’t interchangeable.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy