4.2.6 CMD
A focused guide to CMD, connecting core concepts with practical Docker and container operations.
CMD is the Dockerfile instruction that specifies the default command a container executes when started, unless a different command is explicitly provided at run time — making it the primary way to define what a container does by default.
Basic Usage
CMD is typically written using the exec (JSON array) form, listing the command and its arguments as separate elements.
CMD ["python", "app.py"]
docker run myapp
Running the image with no additional arguments executes exactly this command.
Overriding CMD at Run Time
Because CMD defines a default rather than a fixed requirement, it can be replaced entirely by specifying a different command when starting a container.
docker run myapp python -c "print('different command')"
This entirely replaces the image's default CMD, rather than appending to it.
Shell Form vs. Exec Form
CMD can also be written as a plain string, which Docker wraps in a shell to execute, enabling shell features like variable expansion but losing some of the signal-handling correctness the exec form provides.
CMD python app.py
CMD ["python", "app.py"]
The exec form is generally preferred for application startup, since it makes the application itself the container's main process, correctly receiving termination signals rather than an intermediary shell intercepting them.
CMD in Combination With ENTRYPOINT
When both ENTRYPOINT and CMD are specified, CMD's role shifts to providing default arguments appended to the fixed ENTRYPOINT, rather than defining the entire command.
ENTRYPOINT ["python", "app.py"]
CMD ["--mode", "production"]
docker run myapp --mode development
Why CMD Matters
CMD is what makes an image immediately runnable with a simple docker run, without requiring every caller to specify exactly what should happen — it encodes a sensible default directly into the image itself.