Bird
Raised Fist0
Dockerdevops~15 mins

CMD instruction for default command in Docker - Deep Dive

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of the CMD instruction in a Dockerfile?
easy
A. To expose network ports
B. To set the default command that runs when the container starts
C. To copy files into the container
D. To define environment variables

Solution

  1. Step 1: Understand the role of CMD

    The CMD instruction specifies the default command to run inside the container when it starts.
  2. Step 2: Differentiate from other instructions

    Other instructions like COPY, EXPOSE, and ENV serve different purposes unrelated to the default command.
  3. Final Answer:

    To set the default command that runs when the container starts -> Option B
  4. Quick Check:

    CMD sets default command = C [OK]
Hint: CMD sets container's default run command [OK]
Common Mistakes:
  • Confusing CMD with COPY or ENV
  • Thinking CMD exposes ports
  • Assuming CMD sets environment variables
2. Which of the following is the correct exec form syntax for the CMD instruction to run nginx as the default command?
easy
A. CMD ["nginx"]
B. CMD {"nginx"}
C. CMD ("nginx")
D. CMD nginx

Solution

  1. Step 1: Recall CMD syntax forms

    Docker supports two CMD forms: shell form (string) and exec form (JSON array). The exec form is recommended for clarity and safety.
  2. Step 2: Identify correct JSON array syntax

    The correct JSON array syntax uses square brackets and double quotes: CMD ["nginx"]. Other options use invalid syntax.
  3. Final Answer:

    CMD ["nginx"] -> Option A
  4. Quick Check:

    CMD JSON array uses brackets and quotes = D [OK]
Hint: Use JSON array with brackets and quotes for CMD [OK]
Common Mistakes:
  • Using parentheses or curly braces instead of brackets
  • Omitting quotes around command
  • Using shell form without quotes causing errors
3. Given this Dockerfile snippet:
FROM alpine
CMD ["echo", "Hello World"]

What will be the output when you run the container without overriding the command?
medium
A. No output, container exits silently
B. echo Hello World
C. Hello World
D. Error: command not found

Solution

  1. Step 1: Understand CMD execution

    The CMD instruction runs echo with argument Hello World as the default command inside the container.
  2. Step 2: Predict container output

    Running the container executes echo "Hello World", which prints Hello World to the console.
  3. Final Answer:

    Hello World -> Option C
  4. Quick Check:

    CMD runs echo with args = Hello World [OK]
Hint: CMD JSON array runs command with args exactly [OK]
Common Mistakes:
  • Thinking CMD prints the command itself
  • Assuming no output without explicit print
  • Confusing CMD with ENTRYPOINT behavior
4. Identify the best practice issue in this Dockerfile snippet:
FROM ubuntu
CMD echo Hello World
medium
A. Missing quotes around Hello World
B. FROM instruction is incorrect
C. CMD cannot run echo command
D. CMD should be in JSON array form for best practice

Solution

  1. Step 1: Check CMD syntax

    The CMD instruction here uses shell form without quotes, which is allowed but less safe and less clear.
  2. Step 2: Recommend JSON array form

    Best practice is to use JSON array form like CMD ["echo", "Hello World"] to avoid shell parsing issues.
  3. Final Answer:

    CMD should be in JSON array form for best practice -> Option D
  4. Quick Check:

    Use JSON array for CMD best practice = B [OK]
Hint: Prefer JSON array form for CMD to avoid shell issues [OK]
Common Mistakes:
  • Thinking shell form is invalid syntax
  • Assuming quotes are mandatory in shell form
  • Believing CMD cannot run simple commands
5. You have this Dockerfile:
FROM node:18
CMD ["node", "app.js"]

You want to override the default command to run node test.js when starting the container. Which command will do this correctly?
hard
A. docker run myimage node test.js
B. docker run myimage CMD ["node", "test.js"]
C. docker run myimage --cmd node test.js
D. docker run myimage run node test.js

Solution

  1. Step 1: Understand CMD override

    When running a container, any command after the image name overrides the Dockerfile CMD instruction.
  2. Step 2: Identify correct docker run syntax

    The correct syntax is docker run myimage node test.js. Options with CMD or --cmd flags are invalid.
  3. Final Answer:

    docker run myimage node test.js -> Option A
  4. Quick Check:

    Override CMD by adding command after image name = A [OK]
Hint: Override CMD by adding command after image name in docker run [OK]
Common Mistakes:
  • Using CMD or --cmd flags in docker run
  • Placing command before image name
  • Using invalid docker run syntax
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard