Skip to content
KALANBLON
Show contents

Chapter 2 of 7 · 20 min

Containers and the Dockerfile

By the end of this chapter, you'll be able to

  • Tell an image from a container, and a container from a virtual machine
  • Read and write a simple Dockerfile
  • Order a Dockerfile's instructions to benefit from the layer cache
  • Keep secrets out of images

Image and container

  • an image is a frozen template: a minimal file system, your application, its dependencies and the command to run. It does not change;
  • a container is an image that is running: a process isolated from the rest of the machine, with its own file system. You can start several containers from the same image, like several objects from the same class.

Unlike a virtual machine, which simulates a complete computer with its own operating system, a container shares the host system's kernel: it starts in a fraction of a second and often weighs only a few dozen megabytes. Docker is the best-known tool for building and running containers; Podman is a compatible alternative.

The Dockerfile

An image is described in a text file, the Dockerfile. Here is the one for a small Python web application:

FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
USER 1000
EXPOSE 8000
CMD ["python", "-m", "uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
  • FROM starts from an existing image: here, a slim version of Python 3.13;
  • WORKDIR sets the working folder in the image;
  • COPY copies project files into the image, RUN runs a command during the build;
  • USER 1000 runs the application as an ordinary user rather than as administrator (root): a vulnerability in the application will give an attacker less power;
  • EXPOSE documents the port used, and CMD gives the command run when the container starts.

You build the image with docker build -t shop:1.4.0 ., then run it with docker run -p 8000:8000 shop:1.4.0.

Layers and the cache

Each Dockerfile instruction produces a layer of the image. Docker keeps these layers in a cache: if an instruction and everything before it have not changed, the layer is reused instead of being rebuilt. But as soon as a layer changes, all the following ones are rebuilt. Let's simulate it:

def build(instructions, changed, cache):
    invalid = False
    total = 0
    for instruction, duration, inputs in instructions:
        if invalid or instruction not in cache or inputs & changed:
            invalid = True
            total += duration
            print(f"  rebuilt {instruction:<34} {duration:>3} s")
        else:
            print(f"  cached  {instruction}")
    return total

good_order = [
    ("FROM python:3.13-slim", 0, set()),
    ("COPY requirements.txt .", 1, {"requirements.txt"}),
    ("RUN pip install -r requirements.txt", 95, {"requirements.txt"}),
    ("COPY . .", 2, {"app.py", "requirements.txt"}),
]
cache = {i for i, _, _ in good_order}
print("You change app.py:")
print("total:", build(good_order, {"app.py"}, cache), "s")
You change app.py:
  cached  FROM python:3.13-slim
  cached  COPY requirements.txt .
  cached  RUN pip install -r requirements.txt
  rebuilt COPY . .                             2 s
total: 2 s

By copying requirements.txt alone before installing the dependencies, the long pip install step stays cached as long as the dependency list does not change. Changing the code only costs the last layer.

With the right order, a build after a code change takes a few seconds.

Step 5 of 5
Text description of the animation
  1. The base image has not changed: layer reused.
  2. requirements.txt is identical: layer reused.
  3. Its inputs have not changed: the install is not rerun.
  4. app.py has changed: only this layer is redone.
  5. With the right order, a build after a code change takes a few seconds.

Secrets stay outside

An image is shared: it is pushed to a registry (Docker Hub, GitHub Container Registry, a private registry) from which servers download it. Everything it contains must be assumed readable by anyone with access to it, and even a layer “deleted” by a later instruction remains readable in the image's history. Passwords, API keys and certificates must therefore never be copied into an image: they are provided when the container starts, through environment variables or a secrets manager. A .dockerignore file (modelled on .gitignore) stops COPY . . from shipping a .env file by mistake.

Mini-lab: how much does each change cost?Python 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: reordering a Dockerfile

A Node.js application has this Dockerfile. Every code change reruns npm ci, which takes 80 seconds. Suggest an order that keeps npm ci cached when only the code changes, then check it with the simulation: changing src/index.js must cost less than 5 seconds.

FROM node:24-slim
WORKDIR /app
COPY . .
RUN npm ci
CMD ["node", "src/index.js"]
Hint 1
npm ci only needs package.json and package-lock.json.
Hint 2
Copy those two files, install, then copy the rest.
Show the solution and common mistakes
FROM node:24-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
CMD ["node", "src/index.js"]
def build(instructions, changed):
    invalid, total = False, 0
    for instruction, duration, inputs in instructions:
        if invalid or inputs & changed:
            invalid = True
            total += duration
    return total

manifests = {"package.json", "package-lock.json"}
code = {"src/index.js"}
dockerfile = [
    ("COPY package.json package-lock.json ./", 1, manifests),
    ("RUN npm ci", 80, manifests),
    ("COPY . .", 2, manifests | code),
]
print("code changed:", build(dockerfile, code), "s")
print("dependency added:", build(dockerfile, {"package.json"}), "s")
code changed: 2 s
dependency added: 83 s

Adding a dependency logically reruns the install, but that is rare; the everyday case, changing the code, now only costs 2 seconds.

Common mistakes:

  • Copying package.json without package-lock.json: npm ci requires the lock file, and it is what guarantees identical versions everywhere.
  • Removing the second COPY . .: the image would no longer contain the application's code.

Summary

  1. 1An image is a frozen template; a container is a running image, isolated and lightweight.
  2. 2The Dockerfile describes the image: FROM, WORKDIR, COPY, RUN, USER, CMD.
  3. 3Each instruction is a cached layer; a change invalidates its layer and all the following ones.
  4. 4Copying the dependency files first, then the code, keeps the install cached.
  5. 5Secrets never go into an image: they are provided when the container starts.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.