0
0
Dockerdevops~15 mins

CMD instruction for default command in Docker - Deep Dive

Choose your learning style9 modes available
Overview - CMD instruction for default command
What is it?
The CMD instruction in Dockerfiles sets the default command that runs when a container starts. It tells Docker what program or script to execute inside the container if no other command is given. CMD can specify a command with arguments or just a simple executable. It helps containers know what to do automatically.
Why it matters
Without CMD, containers would not know what to run by default, making them less useful and harder to automate. You would have to specify the command every time you start a container, which is inconvenient and error-prone. CMD makes containers self-contained and ready to run, improving developer productivity and consistency.
Where it fits
Before learning CMD, you should understand basic Docker concepts like images, containers, and Dockerfiles. After CMD, you can learn about ENTRYPOINT, how CMD and ENTRYPOINT work together, and advanced container startup behaviors.
Mental Model
Core Idea
CMD sets the default program and arguments a Docker container runs when started without extra commands.
Think of it like...
CMD is like the default radio station preset in your car; if you don’t choose a station, it plays the preset automatically.
Dockerfile
┌─────────────┐
│ FROM image │
└─────┬───────┘
      │
  ┌───▼────┐
  │  CMD   │  ← default command to run
  └────────┘
      │
  Container starts → runs CMD if no other command given
Build-Up - 6 Steps
1
FoundationWhat CMD Does in Dockerfiles
🤔
Concept: CMD defines the default command and arguments for a container.
In a Dockerfile, CMD specifies what runs inside the container when you start it without extra commands. For example: CMD ["echo", "Hello World"] This means if you run the container normally, it will print "Hello World".
Result
The container runs the specified command automatically when started.
Understanding CMD is key to making containers that do something useful by default.
2
FoundationSyntax Forms of CMD Instruction
🤔
Concept: CMD supports exec form (JSON array) and shell form (string).
There are two ways to write CMD: 1. Exec form (recommended): CMD ["executable", "param1", "param2"] 2. Shell form: CMD executable param1 param2 Exec form runs the command directly, shell form runs it in a shell.
Result
You can choose how the command runs inside the container.
Knowing the syntax helps avoid bugs and unexpected behavior in container startup.
3
IntermediateCMD vs ENTRYPOINT Differences
🤔Before reading on: do you think CMD and ENTRYPOINT do the same thing or have different roles? Commit to your answer.
Concept: CMD sets default arguments or command, ENTRYPOINT sets the fixed executable.
ENTRYPOINT defines the main executable that always runs. CMD provides default arguments to ENTRYPOINT or a default command if ENTRYPOINT is not set. For example: ENTRYPOINT ["ping"] CMD ["localhost"] Running the container runs 'ping localhost' by default.
Result
CMD and ENTRYPOINT work together to control container startup behavior.
Understanding their difference prevents confusion when customizing container commands.
4
IntermediateOverriding CMD at Runtime
🤔Before reading on: if you run 'docker run image ls', does CMD still run or is it replaced? Commit to your answer.
Concept: Commands given at container start override CMD defaults.
If you specify a command when running a container, it replaces CMD. For example: docker run myimage ls This runs 'ls' instead of the CMD command in the Dockerfile.
Result
You can customize container behavior without changing the image.
Knowing how to override CMD lets you reuse images flexibly.
5
AdvancedCMD with ENTRYPOINT Interaction Details
🤔Before reading on: does CMD provide arguments to ENTRYPOINT or replace it? Commit to your answer.
Concept: CMD provides default arguments to ENTRYPOINT if ENTRYPOINT is set in exec form.
When ENTRYPOINT is set in exec form, CMD acts as default arguments. If you run the container with extra arguments, they replace CMD but ENTRYPOINT stays. For example: ENTRYPOINT ["top"] CMD ["-b"] Running container runs 'top -b' by default. Running with 'docker run image -c' runs 'top -c'.
Result
CMD and ENTRYPOINT combine to form flexible container commands.
Understanding this interaction avoids common mistakes in container startup configuration.
6
ExpertWhy CMD Exec Form Is Best Practice
🤔Before reading on: do you think shell form CMD runs as PID 1 or spawns a shell? Commit to your answer.
Concept: Exec form CMD runs the command directly as PID 1, shell form runs via shell which can cause signal handling issues.
Exec form CMD (JSON array) runs the command directly as the container's main process (PID 1). Shell form runs the command inside a shell like '/bin/sh -c', which can cause problems with signals and process management. For example: CMD ["nginx", "-g", "daemon off;"] is better than CMD nginx -g 'daemon off;' because it avoids an extra shell process.
Result
Containers behave more reliably and handle shutdown signals properly.
Knowing this prevents subtle bugs in container lifecycle and improves production stability.
Under the Hood
When a Docker container starts, Docker looks for CMD in the image's Dockerfile. If no command is given at runtime, Docker runs CMD as the container's main process (PID 1). If ENTRYPOINT is set, CMD provides default arguments to ENTRYPOINT. CMD in exec form runs the executable directly, replacing the container's PID 1 process. In shell form, CMD runs inside a shell process, which acts as PID 1 and forwards signals to the command.
Why designed this way?
CMD was designed to provide a simple way to specify default container behavior without forcing it. It separates the executable (ENTRYPOINT) from default arguments (CMD) for flexibility. The exec form was introduced to improve signal handling and process management inside containers, which was problematic with shell form. This design balances ease of use and control.
Container Start Flow
┌─────────────────────────────┐
│ Docker starts container      │
├──────────────┬──────────────┤
│              │              │
│ ENTRYPOINT?  │ No ENTRYPOINT│
│    Yes       │      │       │
│              │      │       │
│ CMD provides │      │ CMD is │
│ default args │      │ command│
│ to ENTRYPOINT│      │ to run │
│              │      │       │
└──────┬───────┘      └───┬───┘
       │                  │
       ▼                  ▼
  Run ENTRYPOINT     Run CMD command
  with CMD args      as PID 1 process
       │                  │
       ▼                  ▼
  Container runs     Container runs
  with combined      default command
  command line
Myth Busters - 4 Common Misconceptions
Quick: Does CMD always run even if you specify a command at docker run? Commit yes or no.
Common Belief:CMD always runs no matter what command you give when starting a container.
Tap to reveal reality
Reality:If you specify a command at docker run, it overrides CMD completely and CMD does not run.
Why it matters:Expecting CMD to run can cause confusion and errors when the container behaves differently than expected.
Quick: Is shell form CMD better for signal handling than exec form? Commit yes or no.
Common Belief:Shell form CMD is simpler and better for running commands inside containers.
Tap to reveal reality
Reality:Shell form CMD runs via a shell process which can cause signal handling and shutdown issues; exec form is better for production.
Why it matters:Using shell form can cause containers to not stop cleanly, leading to resource leaks or stuck containers.
Quick: Does CMD set the main executable or just default arguments? Commit your answer.
Common Belief:CMD sets the main executable that always runs in the container.
Tap to reveal reality
Reality:CMD sets default command or arguments; ENTRYPOINT sets the fixed executable.
Why it matters:Confusing CMD and ENTRYPOINT leads to misconfigured containers that don't run as intended.
Quick: Can you have multiple CMD instructions in one Dockerfile? Commit yes or no.
Common Belief:You can have multiple CMD instructions and they all run in order.
Tap to reveal reality
Reality:Only the last CMD instruction in a Dockerfile takes effect; earlier ones are ignored.
Why it matters:Adding multiple CMDs expecting them all to run causes unexpected container behavior.
Expert Zone
1
CMD in exec form runs as PID 1, which means it must handle Unix signals properly to allow graceful container shutdown.
2
When combining ENTRYPOINT and CMD, CMD acts as default arguments but can be overridden at runtime, enabling flexible container behavior without rebuilding images.
3
Using shell form CMD can cause issues with environment variable expansion and signal forwarding, which is why exec form is preferred in production.
When NOT to use
Avoid using CMD when you need a fixed executable that should never be overridden; use ENTRYPOINT instead. Also, do not use shell form CMD in production containers where signal handling and process management matter. For complex startup scripts, consider using an ENTRYPOINT script instead of CMD.
Production Patterns
In production, Dockerfiles often use ENTRYPOINT to fix the main executable and CMD to provide default arguments. This allows operators to override arguments without changing the image. Multi-stage builds use CMD to set defaults for final images. Monitoring and logging containers use CMD to start the main service cleanly.
Connections
ENTRYPOINT instruction in Docker
CMD provides default arguments to ENTRYPOINT or acts as default command if ENTRYPOINT is absent.
Understanding CMD clarifies how ENTRYPOINT and CMD work together to control container startup, enabling flexible and predictable container behavior.
Unix process signals and PID 1 behavior
CMD in exec form runs as PID 1 inside the container, responsible for signal handling and process reaping.
Knowing how CMD runs as PID 1 helps understand why exec form is preferred and how containers handle shutdown signals gracefully.
Default program settings in operating systems
CMD is like setting a default program to open a file type, providing a fallback when no specific command is given.
This connection shows how default behaviors simplify user experience by automating common actions, similar to how CMD automates container startup.
Common Pitfalls
#1Using shell form CMD causing signal handling issues
Wrong approach:CMD nginx -g 'daemon off;'
Correct approach:CMD ["nginx", "-g", "daemon off;"]
Root cause:Shell form runs command via a shell process that does not forward Unix signals properly, causing shutdown problems.
#2Expecting multiple CMD instructions to run
Wrong approach:CMD ["echo", "First"] CMD ["echo", "Second"]
Correct approach:CMD ["echo", "Second"] # Only last CMD takes effect
Root cause:Dockerfile only honors the last CMD instruction, earlier ones are ignored.
#3Confusing CMD with ENTRYPOINT roles
Wrong approach:ENTRYPOINT ["echo"] CMD ["Hello"] # Thinking CMD sets executable
Correct approach:ENTRYPOINT ["echo"] CMD ["Hello"] # CMD provides default args to ENTRYPOINT
Root cause:Misunderstanding that CMD sets default arguments, not the executable itself.
Key Takeaways
CMD sets the default command and arguments a Docker container runs when started without extra commands.
CMD has two syntax forms: exec form (recommended) and shell form; exec form runs the command directly and handles signals better.
CMD works with ENTRYPOINT by providing default arguments, enabling flexible container startup behavior.
Commands given at runtime override CMD, allowing customization without rebuilding images.
Only the last CMD instruction in a Dockerfile is used; earlier ones are ignored.