Lesson 4 of 8 in Containers with Docker
Writing a Dockerfile
A Dockerfile is a text file of instructions that docker build follows to produce an image. Each instruction adds a layer, and Docker reuses a layer from cache when its instruction and inputs have not changed.
Draft. This lesson is written and waiting for a person to run every command and review it. It is safe to learn from, but check the official documentation for anything you depend on.
Read these first: Running and inspecting containers
The problem this solves
Running someone else's image is only half the job. To ship your own app you need a repeatable recipe that starts from a base, adds your files, installs what is needed and says what to run. Typing those steps by hand into a container and saving it gives you something nobody can review or reproduce.
A Dockerfile writes the recipe down. Because every build follows the same text, the result is the same on your laptop and in CI, and a teammate can read exactly how the image is made.
How it works
- Control
- Data
- Runs code
docker build takes a Dockerfile and the build context, which is the folder you send it, and produces an image.
- Dockerfile to docker build: 1 steps to follow
- Build context to docker build: 2 files for COPY
- docker build to Image: 3 produces
- Control
- Runs code
- Data
Put the rarely changing dependency steps first so they stay cached, and the code that changes often last so only it rebuilds.
- COPY dependency list to RUN install: 1 same, so cached
- RUN install to COPY app code: 2 cached, skipped
- COPY app code to Final image: 3 changed, rebuilt
Read a Dockerfile from the top. FROM picks the base image. WORKDIR sets the folder later steps run in. COPY takes files from the build context into the image. RUN executes a command at build time and keeps the result as a layer. CMD records the command to run when a container starts, and does nothing at build time.
The build context is the folder you pass to docker build, usually .. Docker sends it to the builder, and COPY can only reach files inside it. Large or secret files in that folder are sent too, which is why a .dockerignore file matters.
Docker caches each step. If an instruction and everything it depends on are unchanged, the old layer is reused and the step is shown as CACHED. Once one step changes, every step after it rebuilds, so slow, stable steps go first.
CMD sets the default command and is replaced when you add a command to docker run. ENTRYPOINT makes the container run as a fixed program, and arguments from docker run are appended to it. Use exec form, a JSON array like ["python", "app.py"], so the program receives signals directly.
Try it yourself
You will build a tiny web server image in a throwaway folder. It uses the official Python image only to serve one file.
- 1Create a folder and a page
mkdir -p ~/learn-docker/site && cd ~/learn-docker/site echo 'hello from my first image' > index.html
Everything below happens inside this folder, which you can delete at the end.
- 2Write the Dockerfile
cat > Dockerfile <<'EOF' FROM python:3.13-slim WORKDIR /site COPY index.html . EXPOSE 8000 CMD ["python", "-m", "http.server", "8000"] EOF
EXPOSEonly documents the port. It does not publish it. Publishing is done by-pat run time. - 3Build and run it
docker build -t my-site:1 . docker run -d --name my-site -p 8000:8000 my-site:1 curl http://localhost:8000
The
-tflag names and tags the image. The curl prints your page. - 4Change the page and rebuild
echo 'second version' > index.html docker build -t my-site:2 .
The build output marks the unchanged early steps as
CACHED. Only theCOPYstep and later ones run again. - 5See CMD replaced by a run argument
docker run --rm my-site:2 python -c "print('CMD was overridden')"The default server did not start, because arguments after the image name replace
CMD. - 6Clean up
docker rm -f my-site docker rmi my-site:1 my-site:2 cd ~ && rm -rf ~/learn-docker
This removes only the container, images and folder created in this exercise.
What breaks, and where to look
failed to compute cache key: ... "/index.html": not found (or: COPY failed: file not found in build context or excluded by .dockerignore)
- WHY IT HAPPENS
COPYcan only read from the build context. The file is outside the folder you built from, has a different name or case, or a.dockerignorerule excludes it.- CHECK FIRST
- Check the last argument of your
docker buildcommand, runlsin that folder, and read.dockerignore. Paths inCOPYare relative to the context, not to the Dockerfile's location on disk.
Every build reinstalls all dependencies, even when only one source file changed.
- WHY IT HAPPENS
- A broad
COPY . .sits before the install step. Any file change invalidates that layer, and every later step, including the slow install, reruns. - CHECK FIRST
- Copy only the dependency list first, run the install, then
COPY . .. Watch forCACHEDon each step in the build output.
docker stophangs for about 10 seconds before the container ends.- WHY IT HAPPENS
- The program is not receiving the stop signal, often because
CMDorENTRYPOINTis in shell form and a shell sits in front. Docker waits its grace period, then force-kills it. - CHECK FIRST
- Use exec form with a JSON array in
CMD, and rundocker inspect <name> --format '{{.Config.Cmd}}'to see what Docker actually runs.
When not to use this
- Do not put secrets such as API keys into the Dockerfile with
COPYorENV. They stay in the image layers for anyone who can pull the image. - A Dockerfile is for building one image. To run several containers together, use Compose, covered in a later concept.
Check yourself
What is the build context?
The folder you give to docker build. It is sent to the builder, and COPY can only read files inside it.
Why copy the dependency list before the application code?
So the slow install step stays cached when only your code changes.
What happens to CMD when you add a command after the image name in docker run?
The command you add replaces CMD.
Keep going
Lesson 42 of 92 in the DevOps path