Module 6 Lesson 5: ENTRYPOINT vs. CMD
·DevOps

Module 6 Lesson 5: ENTRYPOINT vs. CMD

Demystify the startup instructions. Learn the subtle but important difference between setting a default command and creating an 'Executable' container.

Module 6 Lesson 5: ENTRYPOINT vs. CMD

This is one of the most common points of confusion for Docker beginners. Both ENTRYPOINT and CMD define what runs when the container starts, but they behave differently when you try to "Override" them from the command line.

1. CMD (The "Default Argument")

CMD provides defaults for an executing container. These can include an executable, or they can omit the executable, in which case you must specify an ENTRYPOINT instruction as well.

  • Behavior: If the user provides a command when running the container (e.g., docker run image ls), the CMD is ignored and replaced by ls.

2. ENTRYPOINT (The "Fixed Instruction")

ENTRYPOINT allows you to configure a container that will run as an executable.

  • Behavior: If the user provides a command when running the container (e.g., docker run image ls), the ls is appended as an argument to the ENTRYPOINT.

3. The "Power Couple" Pattern

The professional way to use these is to use ENTRYPOINT for the executable and CMD for the default flags.

# We are building a "Ping" tool
ENTRYPOINT ["ping"]
CMD ["localhost"]
  • Scenario A: docker run my-ping
    • Result: Runs ping localhost.
  • Scenario B: docker run my-ping google.com
    • Result: Runs ping google.com. (The CMD was replaced, but the ENTRYPOINT stayed!)

4. Shell Form vs. Exec Form

  • Exec Form (Recommended): ["executable", "param1"]
    • Does not start a shell. Correctly receives Unix signals (like SIGTERM for docker stop).
  • Shell Form: executable param1
    • Runs as a sub-process of /bin/sh -c. Does NOT receive signals, meaning docker stop will be slow and violent.

Rule: Always use the Exec Form (with brackets and quotes).


Exercise: The Executable Challenge

  1. Write a Dockerfile using alpine.
  2. Set the ENTRYPOINT to ["echo"].
  3. Set the CMD to ["Hello World"].
  4. Build the image as echo-test.
  5. Run docker run echo-test. What is the output?
  6. Run docker run echo-test Goodbye. What is the output?
  7. How would you "Forcefully" override the ENTRYPOINT if you really needed to? (Hint: check the --entrypoint flag in docker run).

Conclusion of Module 6

You have mastered the Advanced Dockerfile. You can now build high-performance, small, secure, and self-healing images that are ready for the most rigorous production environments.

Next Module: We look at the "Admin" side of Docker: Module 7: Docker Security and Governance.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn