0
0
DockerConceptBeginner · 3 min read

What is CMD in Dockerfile: Explanation and Usage

The CMD instruction in a Dockerfile specifies the default command that runs when a container starts. It sets the main process for the container but can be overridden by command-line arguments when running the container.
⚙️

How It Works

The CMD instruction in a Dockerfile works like setting a default action for your container, similar to how a microwave might have a default cooking time. When you start a container, Docker looks for the CMD instruction and runs the command specified there.

If you think of a container as a small machine, CMD tells it what to do first when it wakes up. However, if you give a different command when starting the container, that command replaces the CMD instruction. This makes CMD flexible because it provides a default but allows changes without editing the Dockerfile.

💻

Example

This example shows a Dockerfile using CMD to run a simple Python script by default.

dockerfile
FROM python:3.10-slim
COPY hello.py /hello.py
CMD ["python", "/hello.py"]
Output
Hello from Docker!
🎯

When to Use

Use CMD when you want to set a default command for your container that runs every time it starts, like launching a web server or running a script. It is helpful when your container has a main task but you want to allow users to override it easily.

For example, if you build a container for a web app, CMD can start the web server automatically. If you want to run a different command temporarily, you can override CMD without changing the Dockerfile.

Key Points

  • CMD sets the default command for a container.
  • It can be overridden by commands given at container start.
  • Only one CMD instruction is allowed per Dockerfile; the last one wins.
  • It is different from ENTRYPOINT, which sets a fixed command.

Key Takeaways

CMD defines the default command run when a container starts.
You can override CMD by providing a different command at runtime.
Only the last CMD in a Dockerfile is used if multiple are present.
CMD is ideal for setting flexible default behavior in containers.