Sub topic 4
Building an image with a Dockerfile
This chapter assumes you can run containers with docker run, work comfortably in a terminal, and have Docker Engine or Docker Desktop installed. Earlier chapters covered what an image is, how layers stack, and how images are named. Here you write the recipe that produces an image.
What a Dockerfile is
A Dockerfile is a plain text file of instructions. docker build reads it from top to bottom, runs each instruction against a working filesystem, and records the result as an image. The file is conventionally named Dockerfile, with no extension.
Each line has the form INSTRUCTION arguments. Instruction names are case-insensitive, but uppercase is the convention. Lines starting with # are comments.
Two kinds of instructions exist:
- Instructions that change the filesystem (
RUN,COPY,ADD) create a new layer holding the changed files. - Instructions that only set metadata (
ENV,WORKDIR,USER,EXPOSE,CMD,ENTRYPOINT,LABEL) are recorded in the image config and add no file content.
The core instructions
| Instruction | Purpose | Adds a layer? |
|---|---|---|
| `FROM` | Sets the base image. Every Dockerfile starts here (only `ARG` may come before it). | Brings in the base layers |
| `WORKDIR` | Sets the working directory for later instructions and for the container. Creates it if missing. | Only if it creates the directory |
| `COPY` | Copies files from the build context into the image. | Yes |
| `RUN` | Runs a command at build time and saves the filesystem changes. | Yes |
| `ENV` | Sets an environment variable that persists into running containers. | No |
| `ARG` | Defines a build-time variable. It is not available in the running container. | No |
| `USER` | Sets the user for later instructions and for the container process. | No |
| `EXPOSE` | Documents a port the application listens on. It does not publish the port. | No |
| `CMD` | Sets the default command, which `docker run` arguments replace. | No |
| `ENTRYPOINT` | Sets the executable, which `docker run` arguments are appended to. | No |
A worked example
Create a directory with two files. The first is a small web server, app.py:
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
body = f"Hello from {os.environ.get('APP_NAME', 'app')}\n".encode()
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
HTTPServer(("0.0.0.0", 8000), Handler).serve_forever()The second is the Dockerfile:
FROM python:3.12-slim
WORKDIR /app
ENV APP_NAME=demo
COPY app.py .
RUN useradd --system appuser
USER appuser
EXPOSE 8000
CMD ["python", "app.py"]Build it, run it, and test it:
docker build -t hello:1.0 .
docker run -d --rm -p 8000:8000 --name hello hello:1.0
curl http://localhost:8000
docker stop helloThe . at the end of docker build is the build context, the directory whose files COPY can see. The next chapter covers it in detail. The -t flag gives the image a name and tag.
To see how the instructions became layers, run:
docker history hello:1.0You will see the base image layers at the bottom. Above them is one row per instruction. Rows for metadata instructions show a size of 0B.
Shell form and exec form
RUN, CMD, and ENTRYPOINT each accept two syntaxes.
- Exec form is a JSON array:
CMD ["python", "app.py"]. Docker starts the program directly, with no shell. - Shell form is a plain string:
CMD python app.py. Docker wraps it as/bin/sh -c "python app.py".
For CMD and ENTRYPOINT, prefer exec form. With shell form the shell is the container's main process (PID 1). It often does not forward SIGTERM to your program, so docker stop waits ten seconds and then kills the container with SIGKILL. Exec form also means shell features such as variable expansion do not happen unless you invoke a shell yourself.
For RUN, shell form is common because you often want &&, pipes, and redirects.
CMD and ENTRYPOINT together
When both are present, ENTRYPOINT is the fixed executable and CMD supplies default arguments:
FROM alpine:3.20
ENTRYPOINT ["ping", "-c", "3"]
CMD ["localhost"]docker run image pings localhost. docker run image example.com replaces only the CMD part and pings example.com. To replace the entrypoint itself, pass --entrypoint.
COPY, ADD, ENV, and ARG
Use COPY for ordinary file copies. ADD also extracts local tar archives and can fetch URLs, and those extras make its behavior less predictable. Use ADD only when you need to unpack a local archive.
ENV values stay in the image and are visible to anyone who runs docker inspect on it. ARG values exist only during the build, and you set them with --build-arg:
ARG PYTHON_VERSION=3.12
FROM python:${PYTHON_VERSION}-slimdocker build --build-arg PYTHON_VERSION=3.11 -t hello:py311 .An ARG declared before FROM can be used in FROM, but it is not visible after FROM unless you declare it again.
Common errors and gotchas
- Deleting files in a later layer does not shrink the image. Layers are additive. If one
RUNdownloads a 200 MB archive and the nextRUNdeletes it, the archive still sits in the earlier layer. Download, use, and delete in the sameRUN. - Secrets baked into layers. A password passed with
ARGorENV, or copied in withCOPY, can be recovered from the image history or layers. Do not put credentials in a Dockerfile. Use BuildKit secret mounts (RUN --mount=type=secret) when a build needs one. - Stale package indexes. Writing
RUN apt-get updateon its own line andRUN apt-get installon another lets the cache reuse an old index. Combine them in oneRUN. COPY failed: file not found. The path is relative to the build context, not to the Dockerfile's location. You cannot copy files from outside the context, such as../config.- Running as root by default. If no
USERis set, the process runs as root inside the container. Create and switch to an unprivileged user as the example does. EXPOSEdoes not publish. The port is reachable from the host only when you pass-por-Ptodocker run.- Unpinned tags.
FROM python:latestcan resolve to a different image next month. Use a specific tag, and later a digest.
Useful build options
docker build -f docker/Dockerfile.dev -t hello:dev .
docker build --no-cache -t hello:1.0 .
docker build --progress=plain -t hello:1.0 .-f selects a Dockerfile with a different name or location. --no-cache forces every step to run again. --progress=plain prints full command output, which helps when a RUN step fails.
Exercise
A Dockerfile has RUN wget https://example.com/data.tar.gz followed by RUN tar -xzf data.tar.gz && rm data.tar.gz. The final image is still larger than the extracted data. Why, and how do you fix it?
Show answer
Each RUN creates its own layer. The first layer stores the downloaded archive, and the second layer only marks it as deleted, so the archive's bytes remain in the image. Combine the commands into one RUN (download, extract, and delete with &&) so the archive never lands in a saved layer.
Exercise
You write CMD python app.py and notice that docker stop takes about ten seconds. What is the likely cause, and what change addresses it?
Show answer
Shell form runs the command under /bin/sh -c, so the shell is PID 1 and may not pass SIGTERM to Python. Docker waits for the grace period and then sends SIGKILL. Switch to exec form, CMD ["python", "app.py"], so Python is PID 1 and receives the signal directly.