What You'll Learn
You'll learn how to use the CMD instruction to define what command runs by default when your container starts—and how to override it when needed.
What CMD Does
The CMD instruction sets the default command that executes when someone runs your container without specifying a command. Think of it like the auto-play setting on a music player: if you just hit "start" without choosing a track, it plays what you've set as default.
Every container needs something to run—otherwise it starts and immediately exits. CMD tells Docker: "If the user doesn't tell you what to do, do this."
Two Forms: Shell vs Exec
Exec form (preferred):
CMD ["executable", "param1", "param2"]
This runs the command directly without invoking a shell. Example:
CMD ["python", "app.py"]
Shell form:
CMD command param1 param2
This wraps your command in /bin/sh -c. Example:
CMD python app.py
The exec form is preferred because it's more explicit, doesn't require shell processing, and handles signals (like Ctrl+C) correctly.
Overriding Behavior
When you run a container, you can override CMD:
# Uses the CMD from Dockerfile
docker run myimage
# Overrides CMD, runs bash instead
docker run myimage bash
Only One CMD Wins
If your Dockerfile has multiple CMD instructions, only the last one counts. All previous ones are ignored.
CMD vs ENTRYPOINT
CMD provides defaults that are easy to override. It's flexible—you can replace the whole command at runtime. (ENTRYPOINT, which you'll learn later, makes the container behave more like an executable.)
Key Takeaway: CMD defines the default command for your container in exec or shell form, but users can override it at runtime—use exec form ["executable", "param"] for best practices.