CMD and ENTRYPOINT instructions to define the default process of a container. You’ll learn how to override or extend these defaults at runtime and bake permanent changes into your images.
Why Containers Exit Immediately
When you run a container without specifying a command, Docker launches the default process defined in the image’s Dockerfile. If that process ends, the container exits:A container only runs as long as its main process is alive. Defining a long-running service or shell will keep it running.
Examining Official Images
Popular Docker images set up their primary service usingCMD or ENTRYPOINT. Let’s look at two examples:
Nginx Dockerfile Excerpt
MySQL Dockerfile Excerpt
The Default Ubuntu Container Runs Bash
The official Ubuntu image usesbash as its default command. Without an interactive TTY, Bash exits immediately:
docker run ubuntu without -t gives Bash no TTY, so it exits immediately—causing the container to stop.
Overriding CMD at Runtime
You can override the defaultCMD by appending your own command in docker run:
sleep 5, keeps the container alive for 5 seconds, then exits.
Making the Change Permanent with CMD
To bake a default command into your image, declare a newCMD in your Dockerfile:
Shell Form vs Exec Form
CMD can use shell form:ENTRYPOINT vs CMD
UseENTRYPOINT to fix the executable but allow arguments to vary:
CMD, any arguments passed to docker run replace the entire command line.
ENTRYPOINT locks in your executable. Combine it with CMD to set default parameters.Combining ENTRYPOINT and CMD
To specify both a fixed executable and default arguments:docker run ubuntu-sleeperrunssleep 5docker run ubuntu-sleeper 10runssleep 10
Always use the JSON array form for both
ENTRYPOINT and CMD when combining them. This ensures proper argument handling.Quick Comparison
| Instruction | Purpose | Override Behavior |
|---|---|---|
| CMD | Default command or parameters | Replaced by arguments on docker run |
| ENTRYPOINT | Fixed executable for the image | Overridable with --entrypoint flag |
Overriding ENTRYPOINT
You can also overrideENTRYPOINT at runtime:
sleep2.0 10 instead of the original sleep.