What Are CMD and ENTRYPOINT in Docker?

What Are CMD and ENTRYPOINT in Docker?

CMD and ENTRYPOINT are the two Dockerfile instructions that decide what program starts when a container comes to life. This guide explains what each one does, how they work together, how they can be overridden, and how to choose between them.

Imagine a coffee machine in an office. It has a button that makes one default drink when pressed, say a regular coffee. But you can also choose a different drink from the menu before pressing. The machine itself always does the same job: it makes hot drinks. The default drink is only a suggestion that you can change. In Docker, ENTRYPOINT is like the machine’s fixed job, and CMD is like the default drink on the menu. Together they decide exactly what happens the moment a container starts.

1The Question Every Container Must Answer

Before learning the two instructions, understand the problem they solve.

A container needs something to run

A Docker image is a read-only package with an application and everything it needs. But an image by itself does nothing. When you create a container from it, Docker must know which program to launch inside. Without that answer, the container would start and immediately end, because a container lives only as long as its main process.

The person who builds the image usually knows best what the program should be. The person who runs the image sometimes wants to change it slightly, for example by giving the program different options. Docker needs a way to let the image author set a sensible default while still letting the runner adjust it.

Simple Analogy

Think of a new phone that arrives with a default ringtone already chosen by the maker. The phone always rings when a call arrives, which is its fixed behavior. The particular sound is only a default, and you are free to pick another one. CMD and ENTRYPOINT give container images the same kind of shape: firm behavior plus friendly defaults.

The main process rule

Whatever program Docker starts becomes the container’s main process, and it is given process number one inside the container. When this process finishes, the container stops. A web server keeps running, so its container stays up. A small script that prints a message and ends makes a container that exits right away. This is why the choice of start command matters so much.

2
Instructions decide the start command: CMD and ENTRYPOINT
1
Main process per container, and it decides the container’s life
Run time
When both instructions take effect, not at build time
i
Good to know

Both CMD and ENTRYPOINT are stored inside the image’s configuration. They do not run while the image is being built. They only take effect later, each time a container is created from the image.

2What Is CMD?

The friendly default that anyone can replace.

CMD sets the default command, or the default arguments, that run when a container starts. The key word is default. It is a suggestion from the image author, and whoever starts the container can replace it simply by typing something else after the image name.

Two jobs, one instruction

Job 1

A complete default command

When there is no ENTRYPOINT, CMD holds the whole program and its options. If nothing else is given, this is what runs.

Job 2

Default arguments for ENTRYPOINT

When an ENTRYPOINT exists, CMD supplies the arguments that are handed to it if the runner gives none of their own.

Key facts about CMD

Only the last one counts

A Dockerfile may contain several CMD lines, but only the final one is used. The earlier ones are simply ignored.

Easy to override

Anything typed after the image name when creating the container completely replaces CMD. This makes it perfect for defaults that people may want to change.

Not part of the build

CMD does not change the image’s files. It only records a note, “when started, do this by default”.

Simple Analogy

CMD is like the “suggested order” printed on a restaurant menu: “Today’s special: soup”. If you say nothing, you get the soup. If you ask for something else, the special is dropped and your choice is served.

3What Is ENTRYPOINT?

The fixed identity that makes a container behave like a single tool.

ENTRYPOINT sets the main executable of the container, the program that will always be launched when the container starts. Unlike CMD, it is not easily replaced. Anything the runner types after the image name is not a replacement, but is added on to the end of the ENTRYPOINT as extra arguments.

This lets an image act like a command-line tool. Suppose an image’s ENTRYPOINT is a converter program. Anyone can then run the image and pass a file name, and the converter receives that name as its argument. The image behaves just like the tool itself.

Key facts about ENTRYPOINT

It defines what the container is

The ENTRYPOINT describes the purpose of the image, such as “this image is a web server” or “this image is a backup tool”.

Extra input is appended

Whatever the runner adds after the image name becomes arguments to the ENTRYPOINT instead of replacing it.

Replacing it takes a deliberate step

Docker provides a special entrypoint option for the run command that swaps in a different program. It must be chosen on purpose, which prevents accidents.

Only the last one counts

As with CMD, if a Dockerfile has several ENTRYPOINT lines, only the last one takes effect.

Simple Analogy

ENTRYPOINT is like the job title on a person’s badge: “Baker”. Whatever you ask this person, they are still a baker. You can hand them different orders, such as a loaf or a cake, but you cannot make them a plumber just by asking. To change their role, you must formally reassign them.

“ENTRYPOINT decides what the container is. CMD decides what it does by default.”

4CMD Versus ENTRYPOINT Side by Side

The two are easy to confuse, so let us compare them directly.

FeatureCMDENTRYPOINT
Main purposeDefault command or default argumentsThe fixed main program of the container
What happens to words typed after the image nameThey replace CMD entirelyThey are added to the end as extra arguments
How easy is it to overrideVery easyNeeds a special option on purpose
Works aloneYesYes
Works togetherProvides default arguments to ENTRYPOINTReceives default arguments from CMD
Best forFlexible defaults, general-purpose imagesImages that act as one specific tool or service
How many countOnly the last oneOnly the last one
!
Common Misconception

Many beginners think CMD and ENTRYPOINT are two ways of saying the same thing. They are not. They react differently to what the runner types, and that difference shapes how your image behaves for everyone who uses it.

Advantages of CMD Alone

  • Simple and familiar
  • Users can easily run something else, such as a shell, for exploring
  • Ideal for general-purpose images with a sensible default
  • Nothing to unlearn when overriding

Disadvantages of CMD Alone

  • Extra words typed by users replace the whole command, which can surprise them
  • Cannot make the image behave like a fixed tool
  • Options must be retyped in full when changed

5Two Writing Styles: Exec Form and Shell Form

Both instructions can be written in two forms, and the choice quietly changes behavior.

Form 1

Exec form

The command and each of its arguments are written as a list of separate items, in the same style as a JSON array. Docker starts the program directly, with no shell in between.

Form 2

Shell form

The command is written as one plain line of text. Docker hands it to a shell, which then starts the program.

Why the form matters

BehaviorExec FormShell Form
Is a shell started first?No, the program runs directlyYes, the shell runs and starts the program
Which process is number one?Your programThe shell, with your program as its child
Stop signalsReach your program directlyReceived by the shell, which usually does not pass them on
Variable substitution such as reading an environment value inside the commandNot done automatically; you must start a shell on purposeDone by the shell
Extra arguments from the runner with ENTRYPOINTAdded to the endIgnored, and CMD is ignored as well
General recommendationPreferred for most casesUse only when you truly need shell features
Simple Analogy

Exec form is like calling a chef directly and giving your order. Shell form is like calling the restaurant reception, who then passes the order to the chef. The extra middle person may not pass along urgent messages, such as “please stop cooking now”.

!
The slow-shutdown trap

With shell form, the shell becomes process number one and often ignores the polite stop request. Docker then waits for the grace period, ten seconds by default, and forcefully kills the container. If your containers always take about ten seconds to stop, this is a likely cause.

i
Need variables in exec form?

If you need a shell feature such as reading an environment value inside the command, you can make the shell the explicit program in exec form. Then it is a conscious choice, and you can arrange for the real program to replace the shell so that it still becomes process number one.

6How CMD and ENTRYPOINT Work Together

The combination is where the design really shines.

When you set both, Docker builds the final command by joining them: first the ENTRYPOINT, then the CMD. The ENTRYPOINT is the program, and the CMD is its default arguments. If the runner adds their own words after the image name, those replace only the CMD part, and the ENTRYPOINT remains in place.

flowchart LR
  E["ENTRYPOINT: the fixed program"] --> F["Final command that runs"]
  C["CMD: default arguments"] --> F
  R["Words typed after the image name"] -.->|"replace CMD only"| C
        
FIG 1 — ENTRYPOINT stays, CMD provides defaults, and typed words replace only CMD
Simple Analogy

Picture a printer. The printer itself is fixed, which is the ENTRYPOINT. The default paper size and quality are the CMD. You can choose different settings for one print job, but you are still using the same printer.

What actually runs in each combination

Your Dockerfile HasWhat Runs by DefaultIf the Runner Adds Words After the Image Name
NeitherWhatever the base image defined; if nothing, the container cannot start meaningfullyThe words are treated as the command
CMD onlyThe CMDThe words replace the CMD
ENTRYPOINT only, exec formThe ENTRYPOINT aloneThe words are added after the ENTRYPOINT
ENTRYPOINT exec form and CMDThe ENTRYPOINT followed by the CMDThe ENTRYPOINT followed by the new words, with CMD dropped
ENTRYPOINT shell formThe ENTRYPOINT through a shell; CMD is ignoredThe words are ignored

A converter tool image

The ENTRYPOINT is the converter program, and the CMD is a default option such as “show help”. Running the image with no words prints the help. Running it with a file name converts that file, because the file name replaces the help option while the converter stays in place.

A web server image

The ENTRYPOINT is the server program, and the CMD is the default configuration file location. Users can point the server at a different configuration file without touching the program itself.

7Overriding at Run Time

The person starting the container has the final say, within limits.

1

Run with no extra words

Docker uses the image’s defaults exactly as written: the ENTRYPOINT plus the CMD, or whichever exists.

2

Run with words after the image name

The words replace the CMD. If an ENTRYPOINT exists in exec form, it stays and receives the new words as its arguments.

3

Run with the entrypoint option

The image’s ENTRYPOINT is replaced with a program of your choice. This is how people open a shell inside an image that normally starts a fixed tool.

flowchart TD
  S["Container is created"] --> A{"Entrypoint option given?"}
  A -->|"Yes"| B["Use that program instead of the image ENTRYPOINT"]
  A -->|"No"| C{"Image has an ENTRYPOINT?"}
  C -->|"Yes"| D["Use ENTRYPOINT"]
  C -->|"No"| E["No ENTRYPOINT is used"]
  B --> G{"Words typed after image name?"}
  D --> G
  E --> G
  G -->|"Yes"| H["Typed words become the arguments or the command"]
  G -->|"No"| I["Image CMD becomes the arguments or the command"]
        
FIG 2 — How Docker decides what to run at start
i
A handy troubleshooting habit

If an image will not start properly, override its ENTRYPOINT with a plain shell and look around inside. You can then try the original command by hand and watch what goes wrong.

!
Where the option goes matters

Options for Docker itself must come before the image name. Everything after the image name is treated as words for the container’s command, not as Docker options. Putting a flag on the wrong side of the image name is a classic source of confusion.

8Signals, Process Number One, and Clean Shutdown

The hidden reason exec form is usually the better choice.

When you stop a container, Docker first sends a polite termination signal to the main process and waits. If the process is still running after the grace period, Docker kills it forcefully. Whether your program receives that polite signal depends on how it was started.

1

Docker sends the stop signal

The signal goes to the container’s main process, which is process number one.

2

The program should react

A well-behaved program finishes its current work, saves data, closes connections, and exits.

3

Docker waits for the grace period

By default this is ten seconds, and it can be changed.

4

A forced kill if needed

If the process is still alive, Docker ends it abruptly, and unsaved work is lost.

Case 1

Exec form, program handles signals

Best case. The program receives the signal directly and exits cleanly and quickly.

Case 2

Shell form

The shell is process number one and typically does not forward the signal, so the program never hears the request and is forcefully killed after the wait.

Case 3

Program ignores signals as process one

On Linux, process number one is treated specially, and programs not written for that role may ignore stop signals even in exec form.

Case 4

Tiny init helper

Docker can run a small helper as process number one that forwards signals and cleans up finished child processes, then starts your program beneath it.

Simple Analogy

Imagine telling a receptionist, “Please tell the manager the fire alarm is ringing.” If the receptionist does not pass the message on, the manager stays in the building. Shell form is that receptionist, and exec form is shouting straight to the manager.

!
Exit code 137

A container that ends with exit code 137 was forcefully killed. If it happens every time you stop a container, the program probably never received or handled the polite stop request. Check the form of your start instruction.

9Entrypoint Wrapper Scripts

A popular pattern for preparing things before the real program starts.

Many official images set their ENTRYPOINT to a small script rather than directly to the main program. This script performs preparation work and then hands control to the real program. The real program is usually supplied by CMD, so users can still choose it when starting the container.

Typical jobs of a wrapper script

Job 1

Prepare configuration

Create or fill in configuration files using environment values passed in at start.

Job 2

Wait for dependencies

Pause until a database or another service is ready to accept connections.

Job 3

Set up folders and permissions

Fix ownership of mounted storage so that an ordinary user can write to it.

Job 4

Run first-time setup

Initialize a fresh database on the very first start, then skip that on later starts.

Job 5

Drop privileges

Start as the administrator to do the setup, then switch to an ordinary user for the real program.

sequenceDiagram
  participant D as Docker
  participant W as Entrypoint script
  participant P as Main program
  D->>W: start the ENTRYPOINT script with CMD as its arguments
  W->>W: prepare configuration and folders
  W->>W: wait for dependencies
  W->>P: replace itself with the main program
  Note over W,P: The main program becomes process number one
  P-->>D: runs and receives stop signals directly
        
FIG 3 — A wrapper script prepares the ground, then hands over to the main program
!
The most important line in the script

The last step of the script should replace the script itself with the main program, rather than simply running the program as a child. Otherwise the script stays as process number one, and stop signals never reach the real program, bringing back the slow-shutdown problem.

Simple Analogy

A wrapper script is like a stage manager who sets the props, checks the lights, and then steps aside so the actors can perform. Once the show starts, the stage manager should not stand in front of the audience.

10Inheritance: What Happens with Base Images

Your image starts from another image, and its settings come along.

When your Dockerfile starts from a base image, it inherits that base image’s CMD and ENTRYPOINT. If you set nothing, the inherited values are used. If you set your own, yours replace them. There is one subtle rule worth remembering: when you define a new ENTRYPOINT in your image, any CMD inherited from the base is cleared, and you must define your own CMD if you want default arguments.

In Your DockerfileWhat Happens to the Base Image’s Settings
You set neitherBoth the base ENTRYPOINT and CMD are inherited unchanged
You set only CMDYour CMD replaces the base CMD; the base ENTRYPOINT is kept, so your CMD becomes its arguments
You set only ENTRYPOINTYour ENTRYPOINT replaces the base one, and the base CMD is cleared
You set bothBoth replace the base values
!
A surprising inheritance effect

If the base image already has an ENTRYPOINT and you only add a CMD, your CMD is not the whole command. It is handed to the inherited ENTRYPOINT as arguments. People often add a CMD expecting a full command to run and get strange errors instead. Always check what the base image already defines.

Checking what you inherited

Inspecting the base image shows its ENTRYPOINT and CMD. A quick look before writing your own settings prevents most surprises.

Multi-stage builds

In a multi-stage build, each stage is its own image. Only the final stage’s CMD and ENTRYPOINT matter for the resulting image, so set them there, not in the early build stages.

11RUN, CMD, and ENTRYPOINT: Build Time Versus Run Time

Three instructions that look alike but act at different moments.

Instruction 1

RUN

Executes a command while the image is being built, and saves the result as a new layer. It happens once, at build time.

Instruction 2

CMD

Records the default command or arguments for when a container starts. Nothing runs at build time.

Instruction 3

ENTRYPOINT

Records the fixed main program for when a container starts. Nothing runs at build time.

QuestionRUNCMDENTRYPOINT
When does it act?During the image buildWhen a container startsWhen a container starts
Does it add a layer of files?Yes, if files changeNoNo
Typical useInstall packages, compile codeDefault start command or argumentsFixed main program
Can the runner change it?No, it is already baked inYes, easilyYes, with a deliberate option
Simple Analogy

RUN is like assembling furniture in the factory, done once before the box is sealed. CMD and ENTRYPOINT are the instructions on the box that explain what to do when the customer opens it at home.

!
Common mistake

Putting the command that starts your application in a RUN step. It would run during the build, finish, and be forgotten. The container would then start with nothing to do, and would exit at once.

12The Same Ideas in Compose and Kubernetes

Other tools let you override these settings using their own words.

You will often start containers through a project file or a cluster platform instead of typing commands by hand. These tools give you ways to override the image’s settings, and it helps to know which names map to which instruction.

WhereOverrides the Image’s ENTRYPOINTOverrides the Image’s CMD
Docker run commandThe entrypoint optionWords typed after the image name
Docker Compose fileThe entrypoint setting of a serviceThe command setting of a service
Kubernetes pod definitionThe command fieldThe args field
i
A naming trap in Kubernetes

In Kubernetes, the field called command replaces the image’s ENTRYPOINT, and the field called args replaces the image’s CMD. The word “command” there does not mean CMD. Mixing these up is very common, so read the names carefully.

One image, many roles

A team builds one image containing their application code. In a project file, the same image is started three times with different commands: one runs the web server, another runs a background worker, and a third runs a scheduled cleanup job. The image stays the same, and only the start command differs.

Database migrations as a one-time job

Before a new release, the same application image is run once with a command that applies database changes and then exits. Afterwards, the normal containers start with their usual command.

13Data Flow: From the Image Configuration to a Running Process

Follow the start command on its journey.

sequenceDiagram
  participant You
  participant Client as Docker Client
  participant Daemon as Docker Daemon
  participant Img as Image configuration
  participant Run as Runtime
  You->>Client: start a container, with optional extra words or options
  Client->>Daemon: send the request
  Daemon->>Img: read stored ENTRYPOINT and CMD
  Img-->>Daemon: defaults from the image
  Daemon->>Daemon: apply overrides and combine into one final command
  Daemon->>Run: create isolated process with the final command
  Run-->>Daemon: main process is running as process number one
  Daemon-->>You: container is up
        
FIG 4 — Docker merges image defaults with your overrides to build the final command
1

Defaults are stored in the image

When the image was built, the author’s ENTRYPOINT and CMD were recorded in its configuration.

2

Overrides arrive with the start request

Any extra words or the entrypoint option are sent along when you create the container.

3

Docker merges them

Following the rules of the earlier chapters, Docker produces one final command list.

4

The process is launched

The runtime starts that command inside the isolated container, and it becomes the main process.

14Security Considerations

The start command is the front door of your container, so treat it carefully.

Do not put secrets in the command

Anything written in CMD or ENTRYPOINT is stored in the image’s configuration, where anyone with the image can read it. Passwords and keys must be supplied at run time through proper secret handling.

Drop administrator rights early

If a wrapper script needs administrator rights for setup, it should switch to an ordinary user before starting the main program, so that the running application has minimal power.

Beware of untrusted input in a shell

Shell form and scripts that build commands from outside input can be tricked into running unintended commands. Prefer exec form and handle input carefully.

Be aware that the entrypoint can be overridden

Anyone who can start containers can replace the ENTRYPOINT with a shell. Protect access to the Docker daemon, and do not rely on ENTRYPOINT as a security barrier.

Keep the image minimal

Very small images, such as distroless ones, may lack a shell entirely. That reduces what an attacker could do, but it also means shell-form commands and wrapper scripts will not work, so plan for it.

!
Reminder

Overriding ENTRYPOINT is a normal feature for debugging, not a flaw. The point is that it is a deliberate action, not that it is impossible.

15Inspecting, Debugging, and Monitoring

How to see what a container is really running, and why it stops.

Tool 1

Inspect the image

A detailed report shows the stored ENTRYPOINT and CMD, plus the working folder and user. This is the first place to check what an image will do.

Tool 2

Inspect the container

The container’s own report shows the final command actually used, after all overrides were applied.

Tool 3

Read the logs

Whatever the main process writes to its output streams is collected and can be read, even after the container has exited.

Tool 4

Check the exit code

Zero suggests a normal finish. Other numbers point to errors, and 137 suggests a forced kill.

Tool 5

Look at the history

The image history lists every instruction, including CMD and ENTRYPOINT, in the order they were applied.

Typical symptoms and what they suggest

SymptomLikely CauseWhat to Check
Container exits immediatelyThe main process finished quickly or crashedLogs, exit code, and whether the start command is a long-running program
Error saying the file or program was not foundWrong path, missing program, or a script with the wrong line endings or no permission to runInspect the final command and check the file inside the image
Container takes about ten seconds to stopThe program never received the stop signalSwitch to exec form and make sure the program handles the signal
Extra words seem to be ignoredENTRYPOINT in shell formUse exec form for ENTRYPOINT
Strange arguments appearAn inherited ENTRYPOINT received your CMD as argumentsInspect the base image
Environment values do not appear in the commandExec form does not use a shell for substitutionUse a shell explicitly, or read the values inside the program
Simple Analogy

Debugging a container that will not start is like figuring out why a car will not start. You check the ignition, which is the start command, the fuel, which is the files and settings, and the dashboard messages, which are the logs and exit code.

16Choosing Between CMD, ENTRYPOINT, or Both

A practical way to decide for your own image.

flowchart TD
  Q1{"Should the image always run one specific program?"} -->|"Yes"| Q2{"Do users often need to pass different options?"}
  Q1 -->|"No, it is general purpose"| CMDONLY["Use CMD only"]
  Q2 -->|"Yes"| BOTH["Use ENTRYPOINT for the program and CMD for default options"]
  Q2 -->|"No"| EPONLY["Use ENTRYPOINT alone, or CMD if flexibility is still wanted"]
        
FIG 5 — A simple decision path for choosing the right instruction

Advantages of Using Both Together

  • The image has a clear, fixed purpose while still offering flexible options
  • Users can pass just the options they care about, without retyping the program
  • Running the image with no words gives a safe and useful default, such as help output
  • Behaves like a real command-line tool
  • Wrapper scripts can prepare the environment and then use CMD as the real program

Disadvantages / Trade-offs

  • More to learn, and easier to misunderstand for newcomers
  • Overriding the program requires the special entrypoint option, which people forget
  • Inherited settings from base images can create surprising combinations
  • Debugging needs a check of both settings to see the final command

General-purpose image, such as a programming language base

Use CMD alone. Users are likely to run many different things, like a shell, a script, or an interpreter session, so replacing the whole command should be effortless.

Single-purpose service, such as a web application

Use ENTRYPOINT for the server, and CMD only for default options that operators may want to tweak.

Command-line tool image

Use ENTRYPOINT for the tool and CMD for a helpful default such as showing help, so that arguments passed by users go straight to the tool.

17Design Patterns and Anti-patterns

Habits worth copying and habits worth avoiding.

Helpful patterns

Pattern 1

Exec form by default

Write both instructions as lists of separate items so the program runs directly and receives stop signals.

Pattern 2

ENTRYPOINT for the tool, CMD for its defaults

Makes the image feel like a proper command-line tool with friendly default options.

Pattern 3

Entrypoint script that hands over

Prepare the environment, then replace the script with the main program so signals flow correctly.

Pattern 4

One image, many commands

Use the same image for web, worker, and job roles, overriding only the start command in each place.

Pattern 5

Helpful default output

Let a tool image print its help when started with no words, so newcomers immediately see how to use it.

Harmful anti-patterns

ANTI-PATTERN-01 Avoid
Problem

Writing ENTRYPOINT in shell form and then expecting CMD or extra words to be passed to it.

Why It’s Harmful

In shell form, the ENTRYPOINT ignores both CMD and any words typed by the runner. The image seems to ignore its users, and the shell also blocks stop signals.

Correct Approach

Use exec form for ENTRYPOINT whenever arguments are expected, and start a shell deliberately only if you need one.

ANTI-PATTERN-02 Avoid
Problem

Using a wrapper script that runs the main program as a child and leaves itself running as process number one.

Why It’s Harmful

Stop signals stop at the script, so the program is killed forcefully after the grace period, losing unsaved work and slowing every shutdown.

Correct Approach

Have the script replace itself with the main program as its final step, so the program becomes process number one.

ANTI-PATTERN-03 Avoid
Problem

Putting the application start command in a RUN step instead of CMD or ENTRYPOINT.

Why It’s Harmful

RUN executes during the build, not at start. The container starts with no command, and it exits immediately, or the build seems to hang while the program runs.

Correct Approach

Use RUN only for build-time work, and use CMD or ENTRYPOINT for what runs when the container starts.

ANTI-PATTERN-04 Avoid
Problem

Placing passwords, tokens, or keys directly in CMD or ENTRYPOINT.

Why It’s Harmful

These values are stored in the image configuration and are visible to anyone who can inspect the image or the container.

Correct Approach

Pass secrets at run time using secret handling, and read them inside the application.

ANTI-PATTERN-05 Avoid
Problem

Starting several unrelated programs from one start command, using tricks to keep them all alive.

Why It’s Harmful

Only the main process is supervised. If a helper dies quietly, nobody notices, and shutdown becomes messy.

Correct Approach

Run one main job per container, and use separate containers for other programs.

18Best Practices and Common Mistakes

A short checklist that saves a great deal of confusion.

1

Prefer exec form

It runs your program directly, receives stop signals, and avoids surprises with arguments.

2

Decide the role of the image

General-purpose images fit CMD alone, and single-purpose tools and services fit ENTRYPOINT with an optional CMD.

3

Put it near the end of the Dockerfile

Since these instructions do not change files, placing them last keeps earlier layers cached when you only adjust the start command.

4

Handle stop signals in the program

Make the application finish work and exit cleanly when it is asked to stop.

5

Make wrapper scripts hand over

End every entrypoint script by replacing itself with the main program.

6

Check the base image first

Inspect inherited settings before adding your own, so you know what you are combining with.

7

Document the intended usage

Note in your image description how users should pass options and how to override the entrypoint for debugging.

Mistakes beginners often make

!
Thinking extra words are added to CMD

Words typed after the image name replace CMD completely. They are only added to the end of an ENTRYPOINT. Mixing this up leads to commands running in unexpected ways.

!
Forgetting that several instructions collapse to one

If you write CMD or ENTRYPOINT more than once, only the last of each is used. Do not expect them to stack.

!
Expecting environment values to expand in exec form

Because no shell is involved, a value written with a dollar sign is passed as plain text. Start a shell on purpose if you need substitution, or let the application read its own environment.

!
Using a program that runs in the background

If the start command launches a program that immediately detaches into the background, the main process ends, and the container stops. The program must stay in the foreground.

!
Script that will not run

An entrypoint script that lacks permission to execute, or that was saved with the wrong line endings from another operating system, fails with confusing “not found” errors. Check both.

19CMD and ENTRYPOINT in the Real World

How these two instructions show up in everyday engineering.

Official database images

Popular database images use an entrypoint script to prepare the data folder and settings on first start, and then hand over to the database server, which is supplied as the default CMD. Users can add server options after the image name.

Web servers and application runtimes

Web server images typically start the server in the foreground by default, so the container stays alive and receives stop signals directly.

Command-line tools packaged as images

Tools for converting files, checking code, or scanning for weaknesses are often shipped as images with the tool as ENTRYPOINT, so users simply pass their arguments and files.

Continuous integration pipelines

Build servers run tool images as throwaway containers, passing different arguments for each job. The same image performs many tasks, with no reinstalling.

Multi-role applications

One application image is started with different commands for the web server, background workers, and scheduled tasks. Companies running many services often rely on this pattern to keep the number of images small.

Debugging sessions

Engineers override the ENTRYPOINT with a shell to explore a broken image, run the original command by hand, and find out why it fails.

GoalSuitable Setup
General-purpose base others will build onCMD only, easy to replace
A service that always runs one programENTRYPOINT in exec form, optional CMD for default options
A tool people call with argumentsENTRYPOINT as the tool, CMD as default help
Initialization before the main programENTRYPOINT script that hands over, with CMD as the real program
Different roles from one imageOverride the command in the project file or cluster definition

20Frequently Asked Questions

Quick answers to what beginners ask most.

Q1What is the main difference between CMD and ENTRYPOINT?

CMD sets a default that is easily replaced by anything typed after the image name. ENTRYPOINT sets the fixed main program, and anything typed after the image name is added to it as arguments.

Q2Can I use both in one Dockerfile?

Yes, and it is a very common pattern. ENTRYPOINT names the program, and CMD supplies its default arguments. In exec form, Docker joins them into one command.

Q3What happens if I define neither?

The image inherits whatever its base image defined. If the base defines nothing either, Docker has no default command, and you must supply one when starting the container.

Q4What if I write CMD several times?

Only the last CMD is used. The same holds for ENTRYPOINT. Earlier ones are ignored.

Q5Can I override ENTRYPOINT when starting a container?

Yes, by using the special entrypoint option before the image name. This is the standard way to open a shell in an image that normally starts a fixed program.

Q6Why does my container stop immediately?

Its main process finished or crashed. Check the logs and exit code, and make sure the start command runs a program that stays in the foreground.

Q7Why does my container take ten seconds to stop?

The program probably never receives the polite stop request, often because shell form is used or a wrapper script does not hand over to the main program. Docker waits for the grace period and then kills it.

Q8Which form should I use, exec or shell?

Exec form is usually better because it runs the program directly and passes stop signals correctly. Use shell form only when you truly need shell features, and understand the trade-offs.

Q9Is CMD the same as RUN?

No. RUN executes during the image build and saves the result in a layer. CMD only records what should happen when a container starts.

Q10How do Compose and Kubernetes relate to these instructions?

They let you override them. In a Compose file, the entrypoint and command settings map to ENTRYPOINT and CMD. In Kubernetes, the command field replaces ENTRYPOINT and the args field replaces CMD.

Q11Where should I put these instructions in the Dockerfile?

Near the end, because they do not change any files. That way, editing them does not force earlier build steps to be repeated.

Q12What should I learn next?

Learn how signals and shutdown work, how environment values and secrets are passed in, how health checks work, and how the container lifecycle behaves. After that, explore project files for running several containers together.

21Summary and Key Takeaways

CMD and ENTRYPOINT are the two Dockerfile instructions that decide what runs when a container starts. ENTRYPOINT sets the fixed main program, the identity of the image. CMD sets the default command or the default arguments, a friendly suggestion that can be replaced. Words typed after the image name replace CMD and are appended to an ENTRYPOINT, and a special option is needed to replace the ENTRYPOINT itself. Written in exec form, the program runs directly as process number one and receives stop signals, while shell form places a shell in between with several side effects. Used together, they let you build images that behave like real tools or services, with clear defaults, easy customization, and predictable, clean shutdowns.

Key Takeaways

  • ENTRYPOINT is the what, CMD is the default how — ENTRYPOINT fixes the main program, and CMD provides a default command or default arguments that are easy to change.
  • Typed words behave differently — they replace CMD entirely, but are appended to an ENTRYPOINT, which can only be replaced with the special entrypoint option.
  • Prefer exec form — it starts your program directly, so it receives stop signals, while shell form puts a shell in between and can ignore CMD and extra words.
  • Only the last of each counts — repeated CMD or ENTRYPOINT lines do not stack, and setting a new ENTRYPOINT clears a CMD inherited from the base image.
  • They act at run time, not build time — RUN works during the build, while CMD and ENTRYPOINT only record what to start later.
  • Wrapper scripts must hand over — prepare the environment, then replace the script with the main program so it becomes process number one and shuts down cleanly.
  • Inspect and know your overrides — check the base image, the final command, logs, and exit codes, and remember that Compose and Kubernetes use their own names, such as command and args, to override these settings.