Building Your First Image
LEVEL 0
The Problem
You have a Dockerfile. Now what? How do you turn this text file into an actual image?
LEVEL 1
The Concept — Compiling the Recipe
The Concept
Writing a recipe doesn’t create food. You have to cook it.
Writing a Dockerfile doesn’t create an image. You have to build it.
docker build is the cooking process. It reads your recipe (Dockerfile), follows each step, and produces the final dish (image).
LEVEL 2
The Mechanics — The Build Command
The Mechanics
Basic Build
docker build -t myapp .
docker build— the command-t myapp— tag/name the resulting image.— the build context (current directory)
Build with Tag and Version
docker build -t myapp:1.0 .
docker build -t myapp:latest -t myapp:1.0 . # Multiple tags
Specify Dockerfile Location
docker build -f Dockerfile.prod -t myapp .
docker build -f path/to/Dockerfile -t myapp path/to/context
LEVEL 3
What Happens During Build
When you run docker build:
- Send build context — Docker packages the directory and sends it to the daemon
- Parse Dockerfile — Docker reads and validates the instructions
- Execute each instruction — Top to bottom, creating layers
- Cache check — Docker checks if each layer already exists
- Create final image — Combine all layers, add metadata
Build Output
$ docker build -t myapp .
Sending build context to Docker daemon 4.096kB
Step 1/5 : FROM python:3.11-slim
---> a3ed95caeb02
Step 2/5 : WORKDIR /app
---> Using cache
---> b7f8e4a8c0d1
Step 3/5 : COPY requirements.txt .
---> 5d2c4f8a3b1e
Step 4/5 : RUN pip install -r requirements.txt
---> Running in 8f3a2b1c4d5e
Successfully installed flask-2.0.0
---> 9e8d7c6b5a4f
Step 5/5 : COPY . .
---> 1a2b3c4d5e6f
Successfully built 1a2b3c4d5e6f
Successfully tagged myapp:latest
Notice:
- Each step gets an ID
- “Using cache” means the layer already exists
- Final image gets the tag
LEVEL 4
Build Caching
Docker caches layers to speed up rebuilds. A layer is reused if:
- The instruction is identical
- All previous layers are identical
- For COPY/ADD: the files haven’t changed
Cache Invalidation
When a layer changes, all subsequent layers must be rebuilt.
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt . # Change here?
RUN pip install -r requirements.txt # Must rebuild
COPY . . # Must rebuild
CMD ["python", "app.py"] # Must rebuild
This is why you COPY dependencies before code — dependency changes are rare, code changes are frequent.