Dockerfile by Example: Command Instruction Structure
CMD provides defaults for an executing container. This sample code explains how it interacts with ENTRYPOINT and how it can be overridden.
Code
FROM ubuntu:22.04
# 1. CMD as a default command
# If no ENTRYPOINT is specified, this is the command that runs.
CMD ["echo", "Hello World"]
# 2. CMD as default arguments for ENTRYPOINT
# See the Entrypoint example for this pattern.
# 3. Shell form (Avoid if possible)
# CMD echo "Hello World"
# This runs: /bin/sh -c "echo "Hello World""Explanation
The CMD instruction serves two main purposes: providing a default command to run if no ENTRYPOINT is specified, or providing default arguments to an existing ENTRYPOINT. Only the last CMD instruction in a Dockerfile takes effect; earlier ones are ignored. Unlike ENTRYPOINT, CMD is easily overridden by specifying a command after the image name in docker run.
Key distinctions of CMD:
- Provide default executable and arguments (if no ENTRYPOINT)
- Provide default arguments for ENTRYPOINT (if ENTRYPOINT exists)
- Overridden completely by any command passed to
docker run - Exec form
["param"]is preferred over shell form
When used without an ENTRYPOINT, CMD defines the entire command execution. This is common for general-purpose base images where the user might want to run different tools (e.g., bash, python, node). Like ENTRYPOINT, the exec form is preferred to avoid the /bin/sh -c wrapper, ensuring the process receives signals correctly and runs as the expected PID.
Code Breakdown
CMD ["echo", "Hello World"] runs echo directly./bin/sh -c.
