liveBook · Manning

Dockerfile

As explained in Fast by Default

A Dockerfile is a text configuration file containing instructions for building a container image.

A Dockerfile is a text configuration file whose instructions build a container image from filesystem layers. Each step records filesystem changes, so build commands directly affect image size and deployment transfer costs. section 8.2.1

Inspect the layers before changing instructions. docker history identifies which command added the most data, while Dive exposes the files inside that layer. Removing files in a later instruction does not remove them from earlier immutable layers. section 8.2.1

Use these practices to keep production images focused:

  • Separate compilation and runtime requirements with multi-stage builds: install tools in a builder stage, then copy only runtime artifacts into a smaller production stage. section 8.2.1
  • Remove package caches during the same build step that creates them, and prefer a slim base image when the application does not need a full distribution. section 8.2.1
Listing 8.6 Inspecting container image layers with docker history
docker history --human --no-trunc your-image:tag #A

Run docker history to connect Dockerfile instructions with the sizes of resulting image layers. section 8.2.1

Listing 8.8 A multi-stage Dockerfile for removing build tools from production
# Build stage with all the tools
FROM python:3.11 AS builder                     #A
WORKDIR /app
COPY requirements.txt ./
RUN pip install --user -r requirements.txt \
    && rm -rf /root/.cache/pip                  #B
 
 
# Production stage with only what's needed
FROM python:3.11-slim                           #C
WORKDIR /app
COPY --from=builder /root/.local /root/.local   #D
COPY . .                                        #E
ENV PATH=/root/.local/bin:$PATH
CMD ["python", "app.py"]

Compare builder and production stages in a Python 3.11 Dockerfile that excludes build tools from the final image. section 8.2.1

How Fast by Default covers it

How deep it goes
Explains layers, immutable filesystem changes, size inspection, caches, base images, and multi-stage builds.
Examples
Uses a checkout API, docker history output, Dive layer browsing, and a Python 3.11 multi-stage Dockerfile.
What it assumes
Assumes familiarity with container images and introduces their layered filesystem model through build inspection.
What you can do after
Diagnose image-size problems with docker history and Dive, then reduce production contents with multi-stage builds.
How it connects
Connects Dockerfiles with container images, image layers, base images, multi-stage builds, Docker, and Podman.

Also explained in

Compare how 21 books explain Dockerfile →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Fast by Default. The section links point to the parts of the book it draws on.