Sub topic 17
Image security basics
This chapter assumes you can write a Dockerfile, build and push images, and refer to an image by tag or digest. It covers the security decisions you make when you build and publish an image, and the mistakes that cause most real incidents.
What you are protecting
An image is a bundle of files that someone else will run. Four things can go wrong:
- The image contains software with known vulnerabilities.
- The image contains secrets, such as tokens or private keys.
- The container runs with more privilege than it needs.
- The image you pull is not the one you intended to pull.
Each of these has a specific control. The diagram shows where each control applies.
Shrink the attack surface with the base image
Every package in an image is a possible vulnerability, and a shell or package manager also helps an attacker who gets in. Choose the smallest base that runs your program.
| Base type | Example | Trade-off |
|---|---|---|
| Full distribution | `debian:12` | Many tools and many packages to patch |
| Slim variant | `debian:12-slim` | Fewer packages, still has a shell |
| Distroless | `gcr.io/distroless/static-debian12` | No shell or package manager, harder to debug |
| Scratch | `scratch` | Empty. Works only for fully static binaries |
Multi-stage builds make this practical. Compilers and build tools stay in the build stage and never reach the final image. A smaller image also has fewer things for a scanner to report.
Do not run as root
By default, a container process runs as root inside the container. Root in a container is not the same as root on the host, but a container escape or a mounted volume turns it into a bigger problem. Set a non-root user in the image.
This Dockerfile extends the multi-stage example from earlier. The distroless nonroot tag already sets user 65532, and the USER line states it explicitly.
# syntax=docker/dockerfile:1
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app ./cmd/app
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/app /app
USER 65532:65532
ENTRYPOINT ["/app"]On a base image that has a shell, create the user yourself, for example with RUN useradd --system --uid 10001 appuser followed by USER appuser. Use a numeric UID where possible. Some orchestrators check for non-root users by number and cannot verify a user name.
You can tighten things further when you start the container:
docker run --rm --read-only --cap-drop ALL --security-opt no-new-privileges myapp:1.0--read-only makes the root filesystem read-only. --cap-drop ALL removes Linux capabilities. no-new-privileges stops processes from gaining privileges through setuid binaries. Your application may need a writable directory or a specific capability, so add those back one at a time.
Keep secrets out of layers
Layers are permanent. If you COPY a key into the image and delete it in a later RUN, the key is still in the earlier layer, and anyone who pulls the image can extract it. The same applies to ARG and ENV values, which are recorded in the image history.
Check an image for leaks:
docker history --no-trunc myapp:1.0Use BuildKit secret mounts when a build step needs a credential. The secret is available only during that one RUN instruction and is never written to a layer. This example downloads private Go modules using a .netrc file:
# syntax=docker/dockerfile:1
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=secret,id=netrc,target=/root/.netrc go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app ./cmd/appdocker build --secret id=netrc,src=$HOME/.netrc -t myapp:1.0 .Add .env, key files, and credentials directories to .dockerignore, as in the build context chapter. That stops a broad COPY . . from picking them up. Runtime secrets such as database passwords should be injected when the container starts, not baked into the image.
Scan for known vulnerabilities
A scanner reads the package lists and files in each layer and compares them with databases of known vulnerabilities (CVEs). Two common tools are Docker Scout and Trivy:
docker scout cves myapp:1.0
trivy image myapp:1.0Keep these points in mind when you read results:
- A scan reports what is known today. An image that passed last month can fail today, so rescan images that are already deployed.
- Many findings sit in packages your program never calls. Prioritize by severity and by whether a fix exists.
- A scan does not prove an image is safe. It finds known problems in recognized packages. It does not find flaws in your own code or a malicious binary it does not recognize.
Many registries can scan on push. Wire a scan into your CI pipeline and fail the build above a severity threshold you choose.
Know what you are pulling
Tags can be moved. golang:1.22 can point to a different image next week, and anyone who can push to a repository can repoint its tags. A digest identifies content, so pulling by digest gives you exactly the bytes you reviewed.
Find the digest of a base image:
docker buildx imagetools inspect golang:1.22Then reference it as golang:1.22@sha256:<digest>, replacing <digest> with the value printed in the Digest: line. When both are present, Docker uses the digest and ignores the tag. The tag stays as a human-readable note.
Pinning has a cost. Your base image stops receiving security updates until you change the digest. Automate that. Tools such as Dependabot and Renovate open pull requests that update pinned digests, so you get reproducible builds and regular patches.
Also prefer these sources:
- Official images and images from verified publishers, over unknown accounts.
- Your own mirror or internal registry for production base images, so a change upstream does not alter your builds.
Registries and tools also support image signing, for example with Sigstore Cosign. A signature proves who published an image, which a digest alone does not. It is worth adopting once the basics above are in place.
Common mistakes
- Using
latestas a base image and never rebuilding. You get unpredictable content and stale packages. - Rebuilding rarely. Patches to the base image only reach you when you rebuild, so schedule rebuilds.
- Installing debugging tools "just in case" in the production image.
- Running
chmod 777or running as root to get past a permission error instead of fixing ownership withCOPY --chown. - Leaving a public repository public by accident. Check repository visibility after the first push.
Exercise
A Dockerfile has COPY id_rsa /root/.ssh/id_rsa, a RUN git clone step, and then RUN rm /root/.ssh/id_rsa. The image is pushed to a registry. Is the key safe? What should you change?
Show answer
The key is not safe. The COPY created a layer that contains the key, and the later rm only hides the file in a newer layer. Anyone who pulls the image can read the earlier layer. Rotate the key. Then rebuild using a BuildKit secret or SSH mount (RUN --mount=type=secret,... or --mount=type=ssh) so the key never enters a layer, and remove the old image tags from the registry.
Exercise
You pin a base image with FROM alpine:3.20@sha256:<digest>. A security fix is published for Alpine 3.20. Does your next build include it? What do you do about this?
Show answer
No. The digest fixes the exact content, so rebuilds keep using the old image. You must update the digest deliberately. Use a tool such as Renovate or Dependabot to propose digest updates automatically, and rescan the image after each update.