Building images
How you build decides whether a deploy takes ten seconds or ten minutes: control the context and respect the cache.
key idea / Docker itselfcontainer / good pathhost / watch outproblem / blockedneutral
The build context
The dot in docker build . is the context: the folder that is uploaded to the daemon.
The layer cache
Docker reuses any layer whose inputs did not change.
Flags worth knowing
| Flag or file | Effect |
|---|---|
-t name:1.0 | tag the image so you can find and run it |
.dockerignore | filters the context: node_modules, .git, build output |
--no-cache | ignore the cache, rebuild every layer |
-f path/Dockerfile | use a Dockerfile that is not named Dockerfile |
Try it yourself
Stay in the greet directory from the previous chapter, or recreate that Dockerfile first.
-
Step 1 · See the context get sent
A large unused file is still part of
.until you ignore it.$ dd if=/dev/zero of=big.bin bs=1m count=20 $ docker build -t greet:1 . # transferring context: 20MB -
Step 2 · Ignore it
$ printf 'big.bin\n' > .dockerignore $ docker build -t greet:1 . # transferring context: a few kB -
Step 3 · Change a source file and watch the cache
FROMandWORKDIRare reused.COPYand everything after it run again, becausehello.txtchanged.$ printf 'hello again\n' > hello.txt $ docker build -t greet:1 . [1/4] FROM docker.io/library/alpine:3.20 CACHED [2/4] WORKDIR /app CACHED [3/4] COPY hello.txt . [4/4] RUN printf 'built in the image\n' > /app/built.txt -
Step 4 · --no-cache rebuilds every layer
$ docker build --no-cache -t greet:1 . [1/4] FROM docker.io/library/alpine:3.20 [2/4] WORKDIR /app [3/4] COPY hello.txt . [4/4] RUN printf 'built in the image\n' > /app/built.txt
Recap
- The build context is uploaded to the daemon, so keep it small with
.dockerignore. - A layer is rebuilt when its inputs change, and so is every layer after it.
- Copy dependency files first, install, then copy your source.
--no-cacheforces a clean rebuild.
Quick check
You edit one source file and the build reinstalls every npm package. What is likely wrong?
Show answer
The Dockerfile copies the whole source before installing dependencies. Copy package*.json, run the install, then copy the source so the install layer stays cached.