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), theCMDis ignored and replaced byls.
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), thelsis appended as an argument to theENTRYPOINT.
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.
- Result: Runs
- Scenario B:
docker run my-ping google.com- Result: Runs
ping google.com. (TheCMDwas replaced, but theENTRYPOINTstayed!)
- Result: Runs
4. Shell Form vs. Exec Form
- Exec Form (Recommended):
["executable", "param1"]- Does not start a shell. Correctly receives Unix signals (like
SIGTERMfordocker stop).
- Does not start a shell. Correctly receives Unix signals (like
- Shell Form:
executable param1- Runs as a sub-process of
/bin/sh -c. Does NOT receive signals, meaningdocker stopwill be slow and violent.
- Runs as a sub-process of
Rule: Always use the Exec Form (with brackets and quotes).
Exercise: The Executable Challenge
- Write a Dockerfile using
alpine. - Set the
ENTRYPOINTto["echo"]. - Set the
CMDto["Hello World"]. - Build the image as
echo-test. - Run
docker run echo-test. What is the output? - Run
docker run echo-test Goodbye. What is the output? - How would you "Forcefully" override the
ENTRYPOINTif you really needed to? (Hint: check the--entrypointflag indocker 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.