Sub topic 13
Fixing findings: base images and multi-stage builds
This chapter assumes you can build Docker images and read a Dockerfile. It also assumes you have run docker scout cves or trivy image and can read CVE IDs, severities, and fixed versions from the earlier chapters. Here you will act on those results. Most findings in an image are not in your code. They come from the operating system packages in the base image and from build tools that were never needed at runtime. The two main fixes are to change what you start from and to change what you ship.
Where findings usually come from
A scanner reports every package it can find in every layer. For a typical application image, that inventory splits into three groups:
- Base image packages: the operating system libraries and utilities, such as
libc,openssl,zlib, andapt. - Build-time packages: compilers, headers, package managers, and
git, installed so the build could run. - Application dependencies: the language packages you install with pip, npm, Go modules, and similar tools.
The first two groups are usually the largest. Fixing them does not need any change to your application code.
| Cause | Typical fix | Effort |
|---|---|---|
| Outdated base image tag | Rebuild on a newer tag or digest | Low |
| Large general-purpose base | Move to a slim or distroless base | Medium |
| Build tools in the final image | Multi-stage build | Medium |
| Vulnerable application dependency | Upgrade the dependency | Varies |
| No fixed version exists | Triage and accept, or switch base | Judgment call |
Step 1: Ask what the scanner recommends
Docker Scout can suggest base image changes for you. Run it against the image you have:
docker scout recommendations nginx:latestThe output lists the current base image and candidate replacements. Each candidate shows how many vulnerabilities it would remove, and whether it is a newer tag of the same image or a different one. Scout can only make this suggestion if it can identify your base image, which it does from the image's provenance attestations or from matching layers. If it cannot, it says so, and you must pick a base yourself.
Treat the result as a shortlist. A candidate with fewer vulnerabilities can still break your application, for example when it uses a different C library or lacks a shell.
Step 2: Update within the same base
The cheapest fix is a newer tag of the same base. Many findings disappear when you rebuild, because the upstream maintainers have already published patched packages. There are two things to watch.
- A tag such as
python:3.12-slimmoves over time. Rebuilding with--pullmakes Docker fetch the current version instead of using a cached copy. - A cached
RUN apt-get upgradelayer will not re-run unless something above it changes. Use--no-cachewhen you want to force fresh package installs.
docker build --pull --no-cache -t myapp:2.0 .
trivy image --severity HIGH,CRITICAL --ignore-unfixed myapp:2.0Pinning by digest (FROM python:3.12-slim@sha256:...) makes builds reproducible, but it also freezes the base. You must update the digest on a schedule, or you will keep shipping the same vulnerabilities. A pinned digest that nobody refreshes is a common source of old findings.
Step 3: Choose a smaller base
Fewer packages mean fewer things to match against a vulnerability database. Common choices, from largest to smallest:
| Base | Contents | Trade-off |
|---|---|---|
| Full Debian or Ubuntu image | Shell, package manager, many utilities | Most findings, easiest to debug |
| `-slim` variant | Reduced Debian with a shell and `apt` | Fewer findings, still familiar |
| Alpine | musl libc, BusyBox, `apk` | Small, but musl can break some native code |
| Distroless | Runtime libraries only, no shell or package manager | Fewest findings, harder to debug |
Moving from a full image to a slim image often removes dozens of low-severity findings in one step. Moving to distroless removes the shell and package manager too, which also removes anything an attacker could use after a break-in.
Test the new base before you rely on it. Alpine uses musl instead of glibc, so some prebuilt Python wheels and Node native modules will not load. Distroless images have no shell, so docker exec -it ... sh fails and RUN instructions cannot run in the final stage.
Step 4: Keep build tools out with multi-stage builds
A multi-stage build uses several FROM lines in one Dockerfile. Each FROM starts a new stage with a fresh filesystem. You compile in an early stage that has the full toolchain, then copy only the result into a clean final stage. The earlier stages are not part of the final image, so their packages are never scanned.
FROM golang:1.22 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /app .
FROM gcr.io/distroless/static-debian12
COPY --from=build /app /app
ENTRYPOINT ["/app"]Here is what each part does:
golang:1.22 AS buildnames the first stage. This image is large and carries a compiler,git, and many system libraries.CGO_ENABLED=0builds a statically linked binary. The binary does not need a C library at runtime, which is why it can run on thestaticdistroless image.COPY --from=build /app /appcopies one file out of the first stage.- The final stage starts from
distroless/static, which contains little more than certificates and timezone data.
The same pattern works for other languages. For interpreted languages the idea is slightly different. You cannot compile to a single binary, but you can install dependencies in a build stage and copy the resulting virtual environment or node_modules directory into a slim runtime stage.
FROM python:3.12 AS build
WORKDIR /app
COPY requirements.txt .
RUN python -m venv /opt/venv \
&& /opt/venv/bin/pip install --no-cache-dir -r requirements.txt
FROM python:3.12-slim
COPY --from=build /opt/venv /opt/venv
COPY . /app
WORKDIR /app
ENV PATH="/opt/venv/bin:$PATH"
CMD ["python", "main.py"]The build stage has the full Python image, which includes compilers needed by packages that build native extensions. The final stage is the slim image and receives only the installed packages.
Step 5: Fix application dependencies
If the scanner reports a package from your language ecosystem, such as a Python package or a Node module, the base image will not fix it. Look at the fixed version in the report, then update the entry in requirements.txt, package.json, or go.mod and rebuild. Check these points first:
- Whether the vulnerable package is a direct dependency or a transitive one. For a transitive one, upgrade the direct dependency that pulls it in, or add a constraint.
- Whether the fixed version is a major version bump. If it is, run your tests before you ship.
- Whether the vulnerable code is reachable. A flaw in a function your application never calls still counts in the report, but the real risk is lower. This feeds into triage.
Step 6: Verify the fix
A fix is only done when the scan shows it. Compare the new image to the old one with Scout:
docker scout compare --to myapp:1.0 myapp:2.0The comparison shows which vulnerabilities were removed, which were added, and which are unchanged. Check the added list too. A new base sometimes removes forty findings and introduces three different ones. Then run Trivy with the same filter you use in CI, so you know the gate will pass:
trivy image --severity HIGH,CRITICAL --ignore-unfixed myapp:2.0Also check image size with docker images myapp. A multi-stage build that did not reduce the size usually did not remove the tools you meant to remove.
Common errors
- Rebuilding without
--pull, so Docker reuses a cached base layer and the findings do not change. - Using
latestas the base tag. Builds are not repeatable, and a scan today may not describe the image you built last week. - Switching to Alpine and finding that a native dependency no longer installs, then returning to the old base without testing slim.
- Copying the entire build stage into the final stage.
- Treating a lower finding count as proof of a better image, without checking that the application still starts and its tests pass.
- Forgetting that a scan describes the image at one moment. New CVEs are published against packages you already shipped, so rescan images on a schedule, not only at build time.
When fixing is not possible
Sometimes no patched package exists, or the only fix needs a base image your application cannot run on. In that case, move the finding to triage. Record why you accept it, who decided, and when you will review it, in the ignore file described in the triage chapter. The gate in the CI chapter then stays strict for everything else.
Exercise
A scan of your Python image reports 40 high findings, and 35 of them are in gcc, make, and libc6-dev, which your application never uses at runtime. You currently use FROM python:3.12 and a single stage. Describe the change that removes most of these findings, and name one way the new image could fail to run.
Show answer
Use a multi-stage build. Install dependencies in a build stage based on python:3.12, then start the final stage from python:3.12-slim and copy only the virtual environment and application code with COPY --from=build. The compilers and development headers stay in the build stage and are not scanned. The new image could fail if a package needs a shared library that the slim base lacks, such as a system library for a database driver. Check by running the container and the tests, then install only the missing runtime library in the final stage.
Exercise
You rebuilt an image with the same Dockerfile and the same FROM python:3.12-slim line, but the Trivy report is identical to last week's. Give two likely causes and a command that addresses both.
Show answer
Docker reused a cached base image and cached RUN layers, or the FROM line is pinned to an old digest. For the cache causes, run docker build --pull --no-cache -t myapp:2.0 ., which fetches the current base and re-runs every layer. If the line is pinned by digest, update the digest to the current one first.