Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 38 ยท Container and Serverless Security

Container Image Security

Learn how to build safer container images: choose small base images, avoid root, keep secrets out of layers, pin versions and scan for known vulnerabilities.

A container image is a stack of read-only layers that holds your application, its libraries and a slice of an operating system. Every layer is code you ship to production, which means every layer is attack surface. If an image contains an old OpenSSL, a forgotten SSH key or a shell that an attacker can use after a breach, the cloud platform around it cannot help much. Image security is the first line of defence for containers because it happens before anything runs.

In this lesson you will learn what makes an image risky, how to build a safer one, and how scanners decide that a package is vulnerable. All tools in this lesson are shown as read-only examples with labelled sample output, and the runnable code is a small stand-in written in Python that you can use to understand the idea. It does not need a Docker daemon or any network access.

Everything here is for images you own or are authorised to assess. Scan your own registry, your own build pipeline and your own test systems only.

What makes an image risky

Most image problems fall into a few groups:

  • Large base images. A full Linux distribution contains hundreds of packages you never use. Each one can carry a vulnerability and each one is a tool for an attacker who gets a shell.
  • Outdated packages. An image built a year ago still contains the libraries of a year ago, even if the application code is new.
  • Running as root. If the process inside the container runs as user root, a container escape bug has far worse consequences.
  • Secrets baked into layers. Anything you COPY or write with RUN stays in the layer history, even if a later step deletes it.
  • Unpinned or untrusted bases. FROM python:latest changes under you, and an unknown publisher's image can contain anything.
flowchart LR
    A["Base image"] --> B["OS packages"]
    B --> C["Language runtime"]
    C --> D["Your dependencies"]
    D --> E["Your code"]
    E --> F["Final image in registry"]
    F --> G["Running container"]

Every layer from the base image to your code ends up in production, so each layer needs a security decision.

Choose a small, trusted base

Start from an image that contains only what your program needs. Common choices are:

Base type Size (typical) Notes
Full distro (ubuntu, debian) 70 to 120 MB Many tools, many packages
Slim variants (debian-slim) 30 to 80 MB Fewer packages
Alpine 5 to 10 MB Tiny, uses musl libc
Distroless 2 to 30 MB No shell, no package manager
scratch 0 MB Empty; good for static Go or Rust binaries

A distroless or scratch image has no shell, so an attacker who finds a code execution bug cannot simply run sh. That does not make you invulnerable, but it removes many easy next steps.

Use official or verified publisher images, and prefer a digest over a tag. A tag such as 1.27 can be re-pointed to a different image tomorrow. A digest such as @sha256:... always names exactly the same bytes.

A safer Dockerfile

The following Dockerfile is shown read-only. It uses a multi-stage build so compilers and test tools never reach the final image, runs as a non-root user and sets a read-only-friendly layout.

DOCKERFILE
# Stage 1: build
FROM golang:1.23@sha256:EXAMPLE_DIGEST_REPLACE_ME 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

# Stage 2: runtime
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/app /app
USER nonroot:nonroot
ENTRYPOINT ["/app"]

Notice what is missing: no latest tag, no apt-get install curl, no source code, no build cache and no root user.

Keep secrets out of layers

Layers are permanent. This is a common and serious mistake:

DOCKERFILE
COPY .env /app/.env
RUN ./build.sh
RUN rm /app/.env

The file is gone from the final filesystem, but anyone who can pull the image can unpack the second layer and read it. Use build-time secret mounts (for example BuildKit --mount=type=secret) and inject runtime secrets through your cloud's secret manager, not through the image. See also secrets scanning in pipelines.

Try it: a mini Dockerfile linter

Real linters such as Hadolint apply dozens of rules. This stand-in applies a handful so you can see how rule-based checks work. Run it and then add a rule of your own.

Python Lint a Dockerfile against basic rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The linter finds four problems in the sample Dockerfile. It is deliberately simple, because it shows the shape of every static check: parse the input, test each rule, collect findings with a severity.

How vulnerability scanners work

A scanner such as Trivy, Grype or a registry's built-in scanner does three things:

  1. Inventory. It unpacks the layers and lists installed packages (from dpkg, apk, rpm, language lock files and so on). This list is called an SBOM, a software bill of materials.
  2. Match. It compares each package name and version with a database of advisories, which come from vendors and public sources such as the CVE and OSV databases.
  3. Report. It prints the matches with severity, the fixed version if one exists and sometimes an exploitability score.

Here is realistic, labelled sample output from a scanner. The package names and identifiers are illustrative.

TEXT
# SAMPLE OUTPUT (illustrative, not from a real scan)
Package        Installed   Fixed In   Severity   ID
libexample     1.1.1k      1.1.1w     HIGH       CVE-0000-0001
zlib-demo      1.2.11      1.2.13     MEDIUM     CVE-0000-0002
busybox-demo   1.31.0      -          LOW        CVE-0000-0003

Try it: a stand-in matcher with version comparison

The hard part of matching is comparing versions correctly: 1.10.0 is newer than 1.9.0, even though a text comparison says otherwise. This stand-in uses a made-up advisory list.

Python Match installed packages against an advisory list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

tinyjson 2.10.0 is correctly reported as not affected by a fix in 2.9.0, because the comparison is numeric. A naive string comparison would have flagged it. Real scanners handle many more version schemes (Debian epochs, semver pre-releases, RPM release numbers).

Scanning in practice

  • Scan on build and on a schedule. A clean image today can have a new advisory tomorrow, so re-scan images already in the registry.
  • Fail the pipeline on severity thresholds, for example block on CRITICAL with a fix available, and track the rest.
  • Rebuild instead of patching in place. Containers are replaced, not updated. Fix the Dockerfile or bump the base image and redeploy.
  • Sign images (for example with Sigstore Cosign) and verify signatures at admission, so only images your pipeline built can run. See kubernetes security basics.
  • Use ignore lists carefully. An accepted risk needs an owner, a reason and an expiry date.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does deleting a secret file in a later Dockerfile step NOT remove it from the image?

    Each instruction creates a layer and earlier layers are kept as they were. Anyone who pulls the image can read the layer that still contains the file.
  2. 2. Which base image choice removes the most tooling an attacker could use after a code execution bug?

    Distroless and scratch images have no shell or package manager, so there is much less for an attacker to use.
  3. 3. Why should a scanner compare versions numerically instead of as text?

    Compared as text, '1.10.0' sorts before '1.9.0', which gives wrong matches. Scanners parse each part of the version as a number.
  4. 4. What is the benefit of pinning a base image by digest?

    A digest is a content hash. A tag is a movable label, so a digest guarantees you build from the image you reviewed.

Summary

  • Every layer of an image is shipped code, so keep images small and build from trusted, pinned bases.
  • Run as a non-root user and use multi-stage builds to leave build tools behind.
  • Never put secrets into layers; deleted files remain in earlier layers.
  • Scanners build an inventory of packages, match versions against advisories and report severity and fixes.
  • Re-scan stored images regularly, rebuild rather than patch, and sign what you build.

Next: Kubernetes Security Basics