# Building images: Dockerfiles, the layer cache and multi-stage builds

Package your own app as an image: write a Dockerfile, order it so rebuilds take seconds, and use a multi-stage build to ship a 14.6MB non-root image instead of a 508MB one with a compiler in it.

Course: [Docker](https://devops.rajeev.pro/courses/docker), lesson 7. About 40 minutes, intermediate. Source: https://devops.rajeev.pro/courses/docker/07-building-images

## What you will learn

- Write a Dockerfile with FROM, WORKDIR, COPY, RUN, ENV, EXPOSE, USER and ENTRYPOINT
- Keep secrets and junk out of the build context with .dockerignore
- Order steps so the layer cache reuses dependencies and only your code rebuilds
- Split build and runtime with a multi-stage build
- Make an image smaller and safer with a minimal base, a non-root user and pinned versions

## The app

Until now, you've run images that somebody else packaged. For your own API, a README listing Go, libraries and
build steps leaves each server to interpret those instructions. One machine can end up with a different toolchain
than another. Build an image from a Dockerfile instead: the image carries the compiled app and its runtime
environment together. In this lesson, you'll package a small Go API, use the layer cache, and compare a basic
image with a multi-stage one.

```go
// main.go
package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
)

func main() {
	version := os.Getenv("APP_VERSION")
	http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "{\"status\":\"ok\",\"version\":%q}\n", version)
	})
	log.Println("price-api listening on :8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}
```

Next to it, `go.mod` (`module price-api` and `go 1.27`). The same ideas apply to a Node, Python or Java app;
only the build commands change.

The source code is the input; the image is the deployable result. Keeping those roles separate means you can
rebuild after a code change without manually preparing each host. The Dockerfile records the steps so another
developer or a CI runner can repeat them. It does not guarantee reproducibility by itself: base image tags,
downloaded dependencies and build arguments still matter, which is why this lesson also covers pinning and
keeping build-only material out of the final image.

## A first Dockerfile

A **Dockerfile** is the recipe. Each instruction is one step, and most steps produce a layer:

```dockerfile
FROM golang:1.27-alpine        # start from an image with Go installed
WORKDIR /src                   # cd into /src (created if missing)
COPY . .                       # copy the build context into /src
RUN go build -o /price-api .   # run a command at build time
CMD ["/price-api"]             # the default command when a container starts
```

```sh
$ docker build -t price-api:single -f Dockerfile.single .
$ docker run -d --name api -p 8090:8080 -e APP_VERSION=1.0.0 price-api:single
$ curl -s localhost:8090/health
{"status":"ok","version":"1.0.0"}
```

The `.` at the end is the **build context**: the folder Docker sends to the builder, and the only files
`COPY` can see. The instructions you'll use most:

| Instruction          | Does                                                                    |
| -------------------- | ----------------------------------------------------------------------- |
| `FROM image:tag`     | the base image; every Dockerfile starts here                            |
| `WORKDIR /path`      | set the working directory for the steps after it                        |
| `COPY src dst`       | copy files from the build context (or another stage) into the image     |
| `RUN command`        | run a command at **build** time, saving the result as a layer           |
| `ENV KEY=value`      | an environment variable, at build time and in containers                |
| `EXPOSE 8080`        | document the port the app listens on (it doesn't publish it: `-p` does) |
| `USER name`          | the user later steps and the container run as                           |
| `ENTRYPOINT` / `CMD` | what a container runs; `CMD` gives default arguments you can override   |

Write `ENTRYPOINT` and `CMD` in the JSON **exec form**, `["/price-api"]`. The shell form (`CMD /price-api`)
wraps your app in `/bin/sh -c`, so the shell becomes PID 1 and may not pass `docker stop`'s SIGTERM on
(the Linux course's _Signals_ lesson explains why that matters).

### .dockerignore

`COPY . .` copies everything in the context. Without a `.dockerignore`, that includes `.git`, `.env` files
with secrets, `node_modules` and editor junk, and any change to them breaks the cache:

```text
# .dockerignore
.git
.env
*.md
Dockerfile*
```

## The layer cache

Every step is cached by its instruction and its inputs. On the next build Docker reuses a step only if
it, and every step above it, is unchanged. The moment one step changes, it and **everything below it**
run again:

> **Figure.** Animated. A six-step Dockerfile: FROM golang, WORKDIR, COPY go.mod, RUN go mod download, COPY . ., RUN go build. First build: every step runs and is saved as a layer. After editing main.go: steps 1 to 4 are CACHED and only COPY . . and go build rerun, so dependencies are not downloaded again. After editing go.mod: steps 1 and 2 are cached, and COPY go.mod and every step after it rerun.
>
> Same Dockerfile, three builds. What changed decides where the rebuild starts.

So the order matters. Copy the dependency list first and download, then copy your code:

```dockerfile
COPY go.mod ./                 # changes rarely (go.sum too, once you have dependencies)
RUN go mod download            # cached until go.mod changes
COPY . .                       # changes on every commit
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /out/price-api .
```

For Node that's `COPY package.json package-lock.json ./` then `RUN npm ci`; for Python,
`COPY requirements.txt .` then `RUN pip install -r requirements.txt`. Here's a real rebuild after changing
one line of `main.go`:

> **Figure.** Real docker build output after changing one line of main.go. WORKDIR, COPY go.mod and RUN go mod download are marked CACHED and take 0.0 seconds. COPY . . runs again, and RUN go build takes 140.7 seconds. Then the final stage copies the new binary and the image is exported.
>
> Steps 2 to 4 are CACHED. Only the copy of the code and the compile run again.

The compile still takes over two minutes on this machine, because Go's own build cache is thrown away with
each layer. A **cache mount** keeps it between builds, outside the image:

```dockerfile
RUN --mount=type=cache,target=/root/.cache/go-build \
    CGO_ENABLED=0 go build -ldflags="-s -w" -o /out/price-api .
```

Package managers have the same trick (`/root/.npm`, `/root/.cache/pip`). The mount never becomes part of
the image.

> **Video.** [Dockerfile Layers & Cache Explained 🐳 | Speed Up Docker Builds (Hands-on) | DevOps Tutorial](https://www.youtube.com/watch?v=RVc_rhd0mbM) (Shubham gour)

## Multi-stage builds

The first image works, but look at it:

```sh
$ docker images price-api
IMAGE              ID             DISK USAGE   CONTENT SIZE
price-api:multi    034074b20fb9       14.6MB         3.24MB
price-api:single   367778fc7a08        508MB          102MB
$ docker run --rm price-api:single du -sh /usr/local/go
282.1M	/usr/local/go
$ docker run --rm price-api:single id
uid=0(root) gid=0(root) groups=0(root),…
```

508MB, of which 282MB is the Go compiler, plus your source code, a shell and package manager, all running
as root. Production needs one file: the binary. A **multi-stage build** compiles in one stage and copies
only the result into a clean one:

```dockerfile
# syntax=docker/dockerfile:1

# Stage 1: build with the full Go toolchain
FROM golang:1.27-alpine AS build
WORKDIR /src
COPY go.mod ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /out/price-api .

# Stage 2: ship only the binary
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/price-api /price-api
USER nonroot
EXPOSE 8080
ENTRYPOINT ["/price-api"]
```

Only the **last** stage becomes the image. `COPY --from=build` reaches back into the build stage for the
binary; the compiler, source and module cache stay behind. `CGO_ENABLED=0` makes a static binary that needs
no C library, and `-ldflags="-s -w"` strips debug symbols. The result is the 14.6MB image above.

`docker build --target build .` stops after a named stage: handy for running tests in the build stage (lesson 13).

> **Video.** [Docker Multi-Stage Builds - Fast and Efficient Dockerfiles](https://www.youtube.com/watch?v=_Q9KSFUZH0c) (Depot)

## Smaller, safer images

| Choice                                                                                                              | Why                                                                                  |
| ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| a **minimal final base**: `distroless`, `alpine`, `-slim`, or `scratch` for static binaries                         | fewer packages, fewer vulnerabilities, faster pulls                                  |
| **`USER`** a non-root user                                                                                          | a compromised app isn't root in the container                                        |
| **pinned** base tags, or digests (`@sha256:…`)                                                                      | rebuilds are repeatable; lesson 8 explains digests                                   |
| `RUN apt-get update && apt-get install -y --no-install-recommends … && rm -rf /var/lib/apt/lists/*` in **one** step | a file deleted in a later layer still ships in the earlier one                       |
| no secrets in `COPY`, `ENV` or `ARG`                                                                                | they stay readable in the image's layers and history; lesson 11 covers build secrets |

Each choice reduces a different risk. A smaller base contains fewer packages to patch and pull. A non-root user
limits what a compromised process can do. Pinned inputs help two builds use the same dependencies. Combining
package installation and cleanup in one layer avoids keeping deleted package indexes in an earlier layer. And
secrets must use a build secret mechanism, because image layers and metadata can be inspected after the build.
These are starting defaults, not proof of safety; scan the final image and verify the user and entry point that
will actually run.

The distroless image has no shell at all, which also means an attacker who gets in has no shell to use:

```sh
$ docker image inspect price-api:multi --format '{{.Config.User}}'
nonroot
$ docker run --rm --entrypoint sh price-api:multi
docker: Error response from daemon: … exec: "sh": executable file not found in $PATH
```

> **Debugging an image with no shell.** Use the `:debug` distroless tag while you investigate, or attach a throwaway container with tools to the running one's namespaces: `docker run --rm -it --pid container:api --network container:api alpine:3.22 sh`. Lesson 13 covers debugging.

`docker history price-api:multi` lists each layer and its size: the only big one is your 5.86MB binary.

> **In production.** Build images in CI from a clean checkout, never on a laptop, and tag them with the commit SHA (lesson 8). Rebuild regularly, even without code changes, so the base image picks up security fixes, and scan the result (lesson 11).

## Image metadata and repeatable builds

`ENTRYPOINT` is the executable; `CMD` supplies default arguments. `ARG` is build-time input, `ENV` is a runtime
default, and neither is a secret store. `HEALTHCHECK` reports process health. Keep `.dockerignore` beside the
Dockerfile so credentials and build output never enter the context.

| Need              | Use          |
| ----------------- | ------------ |
| Fixed executable  | `ENTRYPOINT` |
| Default arguments | `CMD`        |
| Build-only value  | `ARG`        |
| Runtime default   | `ENV`        |

```dockerfile
LABEL org.opencontainers.image.source="https://example.invalid/academy"
ARG BUILD_VERSION=dev
ENV APP_VERSION=$BUILD_VERSION
HEALTHCHECK --interval=30s CMD wget -qO- http://127.0.0.1:8080/health || exit 1
ENTRYPOINT ["/app/server"]
CMD ["--listen=:8080"]
```

BuildKit cache mounts speed installs, secret mounts keep a secret out of layers, and buildx can publish multiple
architectures:

Metadata becomes part of the image's runtime contract. `ENTRYPOINT` says which program starts; `CMD` supplies
defaults that can be replaced when the container is launched. `ARG` exists while building, while `ENV` becomes
a default available when the container runs, so neither should hold a credential. A health check gives the
runtime a signal to inspect, but it must test the service rather than just whether a process exists. Keep
`.dockerignore` aligned with the project so local credentials and generated files never enter the build context.

```sh
$ printf '.git\n.env\nnode_modules\n' > .dockerignore
$ docker buildx build --platform linux/amd64,linux/arm64 --cache-to type=local,dest=.buildx-cache \
    --cache-from type=local,src=.buildx-cache -t example/app:dev .
```

## Mission: Shrink an image from 508MB to under 20MB

Containerise the Go API twice: first with a single-stage Dockerfile, then with a multi-stage one on a distroless non-root base. Prove both answer /health, compare their sizes and users, and show that a code change rebuilds only the last steps.

- You need: Docker, main.go and go.mod from this lesson
- You'll have: Two images, 508MB and 14.6MB, the small one running as nonroot, and a rebuild with CACHED dependency steps

```sh
$ docker build -t price-api:single -f Dockerfile.single .
$ docker build -t price-api:multi .
$ docker images price-api --format '{{.Tag}} {{.Size}}'
multi 14.6MB
single 508MB
$ docker run -d --name api -p 8090:8080 -e APP_VERSION=1.0.0 price-api:multi
$ curl -s localhost:8090/health
{"status":"ok","version":"1.0.0"}
$ docker image inspect price-api:multi --format '{{.Config.User}}'
nonroot
$ sed -i 's/listening/now listening/' main.go && docker build -t price-api:multi . 2>&1 | grep CACHED
$ docker rm -f api
```

Sizes depend on the Go version and base image you pull, but the gap stays the same: the compiler never
reaches production. The `grep CACHED` lines are your dependency steps, reused.

## Try it

- Build the single-stage image and run `docker images` to see its size.
- Change one line of main.go, rebuild, and count the CACHED lines.
- Move `COPY . .` above `RUN go mod download` and see what a code change now rebuilds.
- Build the multi-stage image and compare its size with the first one.
- Try `docker run --rm --entrypoint sh` on the distroless image and read the error.
- Run `docker history` on both images and find the biggest layer in each.

## Quiz

1. You change one line of main.go. Which Dockerfile steps does Docker run again?
   - All of them
   - **The first step whose input changed (the COPY that copies main.go) and every step after it** (answer)
   - Only the last step
   - None, it uses the cache
   Why: Each step is cached by its instruction and its inputs. Once one changes, every step below it is rebuilt, which is why code is copied last.

2. Why copy go.mod (or package.json) and download dependencies before COPY . .?
   - Docker requires that order
   - **Dependencies change rarely, so the download layer stays cached when only your code changes** (answer)
   - It makes the image smaller
   - It is more secure
   Why: With COPY . . first, every code change would invalidate the download and fetch every dependency again.

3. What does a multi-stage build ship?
   - Every stage, merged
   - **Only the last stage, plus whatever it copies from earlier stages with COPY --from** (answer)
   - Only the first stage
   - The build cache
   Why: The compiler, source and build tools stay in the build stage. Here the final image is 14.6MB instead of 508MB.

4. Why add a .dockerignore file?
   - Docker needs one to build
   - **It keeps .git, .env files, node_modules and other junk out of the build context, so they can't end up in the image or break the cache** (answer)
   - It makes Docker ignore errors
   - It hides the Dockerfile from users
   Why: COPY . . copies everything in the context that isn't ignored, secrets included.

5. What do ENTRYPOINT ["/price-api"] and ENTRYPOINT /price-api differ in?
   - Nothing
   - **The exec form runs the program directly as PID 1, so it receives SIGTERM; the shell form wraps it in /bin/sh -c, which may not pass signals on** (answer)
   - The shell form is faster
   - The exec form needs a shell
   Why: Prefer the JSON exec form for ENTRYPOINT and CMD. A distroless image has no shell, so the shell form would not even start.

## Resources

- [Docker Docs: Dockerfile reference](https://docs.docker.com/reference/dockerfile/) (Docker Docs)
- [Docker Docs: build cache](https://docs.docker.com/build/cache/) (Docker Docs)
- [Docker Docs: multi-stage builds](https://docs.docker.com/build/building/multi-stage/) (Docker Docs)
- [Docker Docs: building best practices](https://docs.docker.com/build/building/best-practices/) (Docker Docs)
- [Distroless container images](https://github.com/GoogleContainerTools/distroless) (GoogleContainerTools)
