Stage 1 · Foundations · Chapter 3 of 20 · 8 min read

Dockerfile basics

A Dockerfile is a recipe. Every step becomes a layer, and CMD decides what runs when the container starts.

? What do the diagram colours mean

key idea / Docker itselfcontainer / good pathhost / watch outproblem / blockedneutral

From recipe to layers

Docker executes the file top to bottom and saves the result of each step as a layer.

Dockerfile to layersEach Dockerfile instruction that changes files becomes one layer. CMD only records metadata.DockerfileImage layersFROM alpine:3.20layer 1: base OS filesWORKDIR /applayer 2: empty /app directoryCOPY hello.txt .layer 3: hello.txtRUN printf ... > built.txtlayer 4: built.txtCMD ["cat", "hello.txt"]metadata only, no files
Read the Dockerfile top to bottom; the image stacks the same steps bottom to top.

Build time versus run time

The confusion between RUN and CMD disappears once you separate the two moments.

Build time versus run timedocker build (once)FROM · COPY · RUNexecuted, results saved as layersImageready to shipdocker run (every start)CMD / ENTRYPOINTbecomes the main processContainerPID 1 is that processimage
RUN and COPY happen once, at build. CMD happens every time a container starts.
CMD versus ENTRYPOINTWith CMD, extra words on docker run replace it. With ENTRYPOINT, they become its arguments.CMD ["cat", "hello.txt"]docker run imgcat hello.txtdocker run img lsls (CMD replaced)your words replace the defaultENTRYPOINT ["ping"]docker run img hping hdocker run img -c 1 hping -c 1 hyour words become arguments

The instructions you will use daily

InstructionJobCan be replaced by docker run image ...?
RUNruns at build time, adds a layerno, already baked in
CMDdefault command at startyes: whatever you type replaces it
ENTRYPOINTfixed program at startno, your words become its arguments
COPYhost files into the imageno (use -v for runtime files)
ADDCOPY plus URLs and tar extractprefer COPY; ADD surprises people

RUN vs CMD in plain words

Both run commands. The difference is when.

Analogy: packing a lunchbox. RUN is cooking and packing the food. You do it once, in the kitchen, and the result goes into the box. CMD is the note on the lid: “When you open this, eat the sandwich.” Writing the note does nothing by itself. It’s followed every time someone opens the box.

In a Node app’s Dockerfile:

RUN npm ci --omit=dev      # build time: installs packages INTO the image
CMD ["node", "server.js"]  # start time: what each container runs

npm ci runs once during docker build, and the installed node_modules become part of the image, so every container starts with them already there. CMD does nothing during the build. At docker run, Docker reads it and starts node server.js inside the new container.

RUNCMD
When it runsdocker builddocker run (container start)
How oftenOnce per buildEvery time a container starts
ResultSaved into the image as a layerA running process
Several in one fileAll run, in orderOnly the last counts
Typical useInstall packages, compile, create foldersStart your app or server
Override at docker run?No, it’s baked into the imageYes: words after the image name replace it
Common mistakeRUN node server.js tries to start your server during the build. The server never exits, so the build hangs. Even if it finished, nothing would be left running, because a build doesn’t keep processes alive. Quick test: should the result be saved inside the image? Use RUN. Is it what should happen every time a container starts? Use CMD.

Try it yourself

Work in an empty directory. Each instruction below becomes one layer.

  1. Step 1 · Write the files
    $ mkdir greet && cd greet
    $ printf 'hello from the image\n' > hello.txt
    $ cat > Dockerfile << 'EOF'
    FROM alpine:3.20
    WORKDIR /app
    COPY hello.txt .
    RUN printf 'built in the image\n' > /app/built.txt
    CMD ["cat", "/app/hello.txt"]
    EOF
  2. Step 2 · Build, and read each step

    The numbers are the Dockerfile instructions. FROM downloads Alpine. WORKDIR creates /app. COPY adds hello.txt. RUN writes built.txt into the image.

    $ docker build -t greet:1 .
    [1/4] FROM docker.io/library/alpine:3.20
    [2/4] WORKDIR /app
    [3/4] COPY hello.txt .
    [4/4] RUN printf 'built in the image\n' > /app/built.txt
    naming to docker.io/library/greet:1
  3. Step 3 · CMD is the default process
    $ docker run --rm greet:1
    hello from the image
  4. Step 4 · A command on docker run replaces CMD

    The file from RUN is in the image, so this container can read it. --rm deletes the container when cat exits. The image stays.

    $ docker run --rm greet:1 cat /app/built.txt
    built in the image
    $ docker images greet
    REPOSITORY   TAG   IMAGE ID       SIZE
    greet        1     9f0c1a2b3c4d   8MB
Common mistakeWriting CMD node server.js in shell form. It runs under /bin/sh, so the stop signal goes to the shell instead of node, and docker stop waits 10 seconds before killing it. Use the exec form: CMD ["node", "server.js"].

How a command on docker run replaces CMD

Step 4 ran docker run --rm greet:1 cat /app/built.txt, and hello.txt was never printed. Here is why.

CMD is written on the image’s settings card

An image is not just files. Docker also saves a small settings card (its config) with it. CMD ["cat", "/app/hello.txt"] doesn’t run anything at build time. It writes Cmd = [cat /app/hello.txt] on that card. You can read the card yourself:

$ docker inspect greet:1 --format '{{.Config.Cmd}}'
[cat /app/hello.txt]

Words after the image name are the command

Docker reads docker run in this shape:

docker run [options]  IMAGE     [command to run]
docker run --rm       greet:1   cat /app/built.txt

Options such as --rm go before the image name. Everything after it is the command. Then Docker follows one rule:

You typeDocker runs
docker run --rm greet:1The card’s default: cat /app/hello.txt
docker run --rm greet:1 cat /app/built.txtYour command: cat /app/built.txt

It’s a straight swap, not a merge. The default command doesn’t run at all, before or after. The swap only applies to the container this one command creates. The image isn’t changed, so the next plain docker run greet:1 gets the default back. That’s why the instruction is a default command: it’s used only when you don’t give one.

Analogy: a café. The menu says “Today’s default: coffee” (CMD). Say nothing and you get coffee. Say “tea, please” (cat /app/built.txt) and you get tea, and no coffee. The menu isn’t rewritten. The next customer who says nothing still gets coffee.

The whole run, step by step

PartJob
docker runCreate a new container and start it
--rmDelete the container automatically when it finishes
greet:1The image: name greet, tag 1
cat /app/built.txtThe command to run inside the container. It replaces CMD for this run
  1. 1 · Find the image

    greet:1 is already local from docker build, so nothing is downloaded.

  2. 2 · Create a container

    A fresh container whose files are a copy of the image’s, including /app/built.txt, which RUN wrote at build time.

  3. 3 · Start your command inside it

    cat /app/built.txt becomes the container’s main process. It reads the container’s own files, not your machine’s folders.

  4. 4 · Output reaches your terminal

    There’s no -d, so you’re attached and Docker forwards what cat prints (chapter 2).

  5. 5 · cat exits, so the container stops

    A container lives exactly as long as its main process, which here is a split second.

  6. 6 · --rm deletes the container

    Only the unchanged image is left.

Try itChange the RUN line to RUN date > /app/built.txt and rebuild. Run cat /app/built.txt twice: the time is the same both times, because it was written once, at build. Rebuild with docker build --no-cache -t greet:1 . and you get a new time. Without --no-cache, Docker may reuse the saved step and keep the old time.

The exception: ENTRYPOINT

ENTRYPOINT is not replaced this way. With an ENTRYPOINT, the words after the image name are added to the end of it instead (the CMD vs ENTRYPOINT diagram above shows both cases). When both are set, CMD supplies the default arguments:

ENTRYPOINT ["node"]
CMD ["server.js"]

$ docker run app            # runs: node server.js
$ docker run app other.js   # runs: node other.js   (only CMD was swapped)

To replace an ENTRYPOINT you need the separate flag --entrypoint. A Dockerfile with only CMD, like greet, gets the simple swap.

Recap

Quick check

A Dockerfile has two CMD lines. What runs?

Show answer

Answer: Only the last CMD.

Only the last one. Earlier CMD lines are ignored. Use ENTRYPOINT when the command must not be replaced by arguments.

Where does npm ci belong: RUN or CMD?

Show answer

Answer: RUN: it runs once at build time and its result is saved as a layer.

RUN, so the result is baked into the image. CMD is the command that starts your app.

The image has CMD ["cat", "/app/hello.txt"]. What does docker run --rm greet:1 cat /app/built.txt print?

Show answer

Answer: Only built.txt. Your command replaced CMD for this container.

Words after the image name replace CMD. The image is unchanged, so a plain docker run greet:1 still prints hello.txt.

Dockerfiles: common questions

What is the difference between CMD and ENTRYPOINT?

ENTRYPOINT sets the program that always runs. CMD gives default arguments, or a default command, that docker run arguments replace.