Back to Articles

Container Security: From Build to Runtime

Contents

The Supply Chain as an Attack Surface

The threat model for containers moved from "who can talk to my service" to "which artifact in my chain can be swapped or broken without me noticing." The stages, and the failure at each:

  • Base image. Your single biggest dependency. A malicious or compromised base — a typosquatted Docker Hub name, a maintained image with a bad update — puts the attacker in every image you build from it, including ones you already deployed.
  • Dependencies. The long tail of libraries. One compromised package lands in every image that builds it, and the compromise may be a single version that looks otherwise innocent.
  • Build pipeline. The build machine is part of the supply chain too: a trojaned CI runner, an untrusted build cache, a base image pulled without a digest pin. The pipeline that builds the artifact is as much an artifact as the artifact.
  • Registry. The storage point. Weak registry access means anyone with the credentials can push an image with your name — and the cluster will happily pull it. The registry is where provenance is either enforced or merely assumed.
  • Runtime. The node. A runtime escape turns a workload compromise into a node compromise, and a node compromise into a foothold in the cluster. The runtime is where the previous four stages' failures become incidents.

The organizing principle for everything below: each control is placed at the stage where its risk exists, and each stage assumes the previous stage failed. Signing doesn't make scanning redundant; scanning doesn't make admission control redundant. The chain is the perimeter.

Build-Time Hardening

Most of the runtime risk you'll ever face is decided in the Dockerfile. Four decisions do most of the work:

  • The right base image. Small and supported: distroless, or a slim variant of a distro you'll actually patch. Fewer packages means fewer CVEs and a smaller attack surface, and the base is the one dependency you inherit wholesale. Pin it by digest when the environment demands it, and track it like any other dependency — because it is one.
  • Non-root user. A USER directive, a non-root UID. A workload that escapes as non-root has dramatically less to do on the node — it can't write to arbitrary paths, bind privileged ports, or touch the kubelet's socket. This is the single highest-leverage line in a Dockerfile.
  • Minimal attack surface. No shell, no package manager, no debugging tools in the production image. Every tool that ships is a binary an attacker can execute. The build tools don't ship — which is what multi-stage builds are for.
  • Multi-stage builds. Compile and package in a stage that has the toolchain; copy only the artifact into a stage that doesn't.
# Multi-stage: the build toolchain never ships.
FROM golang:1.22-alpine AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download          # dependencies fetched in the build stage only
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app ./cmd/server

# Runtime stage: just the static binary, no shell, no toolchain.
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/app /app
USER nonroot:nonroot
ENTRYPOINT ["/app"]

The last two lines are the whole argument for the exercise: distroless has no shell (no /bin/sh to drop into, no package manager to fetch a tool), and nonroot is the image's built-in non-root user. An image like that doesn't just scan cleaner — it gives the attacker nothing to work with even if a vulnerability in the app is exploitable.

Scanning in CI

Two scanners cover most estates: Trivy[1] and Grype[2]. Both scan images (and SBOMs, filesystems, git repos), both are run in CI on every build, and both need a second, scheduled pass against the registry — because a new CVE published after your image was clean changes the answer. The scan-at-build catches what was known then; the scheduled rescan catches what's known now.

Where teams go wrong is the policy. Gating on CVE count is the classic error, because CVE count is a weak signal — the scanner output carries several better ones:

SignalWhat it tells youHow to use it
CVE ID + CVSS severityThe traditional filter. Severity is a static score, not a risk assessmentBaseline filter only — a critical-score CVE with no known exploit path is not an emergency
EPSS scoreEstimated probability of exploitation in the wild over the next 30 days — a risk-adjusted signalThe primary triage input: high EPSS means the vulnerability is likely to be targeted, not just possible
Fix availabilityWhether a patched version exists for the affected componentUnfixed CVEs need a compensating control (patch window, network restriction), not a build block you can't satisfy
Exploit contextWhether a proof of concept or active exploitation is documentedThe difference between "a CVE exists" and "a CVE is being used" — the line that should trigger a page
Component classOS package vs. application dependencyDifferent patch paths: a base image update vs. a dependency bump. The fix owner differs

Rule of Thumb: A good scan policy is one sentence a new engineer can repeat: "block the build on critical vulnerabilities with known exploits where a fix exists — track everything else." An image with 40 benign CVEs and no exploitable path is safer to run than an image with 3, one of which is under active exploitation. Gate on exploitability, not count — the count is a vanity metric that makes the team immune to the signal that matters.

One operational note: the scanner database is a dependency. An image scanned against a three-week-old database is a scan against a world that no longer exists, so the rescan schedule and the DB update frequency are part of the control, not the plumbing.

Signing and Verification

Scanning identifies components and known findings; signing lets a verifier check the artifact's recorded build identity and integrity. In Sigstore's[3] keyless model, cosign uses an OpenID Connect (OIDC) identity from the CI job, Fulcio issues a short-lived signing certificate, and Rekor records the signing event in a transparency log. This avoids a long-lived signing key in the pipeline, but the verifier must still constrain the trusted issuer, repository, workflow, and artifact digest. Enforce those checks at admission so the runtime platform decides which images may execute.

# Sign in CI, after build, before push (or right after):
# keyless — the identity is this GitHub Actions workflow, no key material
cosign sign --yes registry.example.com/app/api:2026.08.19

# What the admission policy enforces (and what a reviewer can run locally):
# the signature must be tied to this specific workflow's identity.
cosign verify registry.example.com/app/api:2026.08.19 \
  --certificate-identity "example-org/api-app/.github/workflows/release.yml@github" \
  --certificate-oidc-issuer "https://token.actions.githubusercontent.com"

At the cluster, a Kyverno[4] (or OPA) admission policy requires a valid signature from a known workflow before any workload from your registry is admitted. The point of verifying at admission rather than only in CI is that the registry and the cluster are separate trust domains: a signature is bound to an image digest, so an image that's replaced, re-pushed, or pushed by something else fails verification at the gate. The signature is the provenance check that survives a compromised pipeline, a stolen registry credential, or a typosquat — because all three produce an image that isn't the one your workflow signed.

Plan explicitly for disconnected verification. Public keyless signing needs the Sigstore services at sign time. Verification can be performed offline when the signature is packaged with a Sigstore bundle containing the certificate, timestamp, and transparency-log proof, and the verifier already has the required trust roots. Another air-gapped option is cosign with an internal key pair or a private Fulcio deployment. Confirm the current cosign bundle format and the exact certificate identity your CI provider issues before building the admission policy.

Registry Hygiene

The registry is where provenance is enforced or assumed, and the controls are unglamorous and effective:

  • Access control. Per-repository RBAC, short-lived scoped tokens, no shared push credentials. The CI for team A gets read access to team B's images, not push. A registry where everyone can push to everything is a registry where everyone can be attacked through everyone else.
  • Image lifecycle. An immutable tagging scheme — date or build ID, never a moving target — retention and garbage collection, and a rule that production references only immutable tags. "Which exact image is prod running, and did it change since the audit?" should be answerable from the tag alone.
  • What to block, explicitly. latest tags in production (a rebuild is a silent change with no diff to review); unsigned images (admission denies, not warns); images from registries outside the estate (only your registry is in scope); and images that weren't built by your pipeline (provenance check, not trust). Each of these is a one-line admission policy that closes a whole class of incident.

The registry is also where the scheduled rescan lives, because that's where the estate's actual image inventory is. Scan the registry on a schedule, and the "which of our images contain the library that just got patched" query becomes a report instead of a rebuild-and-grep marathon.

Runtime: Policy, Confinement, Detection

The runtime layers split into two jobs: prevention (static policy that makes bad configurations impossible) and detection (dynamic observation that catches what the policy missed). You need both, because prevention assumes you wrote the policy right, and detection without prevention is just late notice. The layers, from cheapest to most operational:

LayerToolsWhat it catches
Pod security (admission)Pod Security Standards in enforce mode, OPA/Kyverno policiesUnsafe pod specs: privileged containers, host namespaces, missing seccomp — before the pod ever schedules
Confinementseccomp profiles, AppArmorDisallowed syscalls and file-access patterns at the process level — the blast radius of an in-container exploit
Runtime detectionTetragon, Falco (eBPF)What the static controls miss: a process that execs a shell, a new network listener, a write to a sensitive path, credential-file access — matched against policy or anomaly rules
NetworkNetworkPolicy, CNI enforcementEast-west movement between workloads that shouldn't talk — the lateral-movement path after a compromise
HostNode agents, file integrity monitoringNode-level compromise indicators: unexpected binaries, modified system files — the signal that the escape happened

Pod Security Standards in restricted mode on production namespaces is the highest-value runtime control per unit of effort — it's a mode flag plus a few admission policies, and it closes the whole class of "the pod spec was privileged" incidents. eBPF is what makes the detection layer cheap enough to leave running: it is a Linux kernel facility for loading small, sandboxed programs into the kernel itself, so a tool can watch every system call a container makes without a custom kernel module and without sitting in the data path. The eBPF-based tools (Tetragon for policy-driven probes, Falco for rule-based syscall monitoring)[5] are the layer that turns "we have controls" into "we know when a control fails," and they're the difference in an incident between finding out at the post-mortem and finding out at the alert.

SBOMs

Every image you build should ship with a Software Bill of Materials — CycloneDX or SPDX — generated in the build pipeline and stored with the image. An SBOM is the complete, machine-readable list of what's in the artifact, which sounds redundant with the scanner and isn't: the scanner answers "is there a problem today," the SBOM answers "what exactly is in this, so we can answer any question tomorrow."

Two reasons the SBOM moved from nice-to-have to expected. First, regulatory and procurement: US federal software procurement requires SBOMs (the executive order on improving the nation's cybersecurity), and the requirement is spreading to state, local, and utility procurement and to insurance questionnaires — the estate that builds water-utility or government-adjacent software will get asked. Second, incident response: when a vulnerability is disclosed in a dependency, the SBOM turns "which of our images contain this?" from a multi-day rebuild-and-grep exercise into a query answered in minutes, across the registry, against every image you've ever built. The SBOM is what makes the scheduled rescan's findings actionable at fleet scale instead of per-image.

Stage by stage, the control map looks like this[6]:

StagePrimary riskControls that matter
Base imageMalicious or compromised upstreamDigest pinning, trusted registries only, scanning, base image tracked as a dependency
BuildPipeline compromise, image bloatMulti-stage, non-root, minimal base, pipeline isolation, signed build identity
Image (vulnerabilities)Known CVEs in dependenciesCI scan plus scheduled rescan, exploitability-based policy, SBOM
RegistryUnauthorized push, image substitutionRBAC, short-lived tokens, signing, immutable tags, lifecycle/retention
RuntimeEscape, lateral movementPod Security (restricted), seccomp/AppArmor, eBPF detection, network policy, admission verification of signatures
IncidentSlow blast-radius mappingSBOMs across the fleet, registry-level rescan, detection alerts

When Not to Go Deep — and Who Owns What

The full stack above can suit a multi-team platform estate. An air-gapped environment requires a different design:

  • Air-gapped estates. A private registry, an offline scanner database synced across the boundary on a schedule (Trivy's offline mode exists for exactly this), and internal signing — your own key pair or an internal Fulcio, with the public key or CA in the admission policy. What still applies, unchanged: non-root builds, minimal bases, Pod Security in restricted, seccomp, network policy, and SBOMs. None of those depend on the internet; they depend on the artifact pipeline existing at all, which is the air-gapped estate's real prerequisite. What doesn't transfer: the public transparency log, which you replace with your own record-keeping.
  • Small estates. Three nodes and a handful of workloads doesn't need eBPF detection running in prod — the alert noise will eat the team. Pod Security plus signing plus scanning is the 80/20, and detection can wait until the estate is big enough for the signal to be worth the noise. The layer to never skip, at any size, is the non-root user in the Dockerfile — it's one line and it's the last line of defense before the node.

And the division of labor, because the chain only holds if each stage has an owner:

  • Developers own: the Dockerfile (non-root, minimal, multi-stage), dependency currency, a scan-clean image, and the SBOM generated at build.
  • Platform owns: the registry access model and lifecycle, the admission policy (signatures, pod security), the runtime layer (restricted mode, eBPF), the scheduled rescan, and the signing infrastructure — the trust anchors the developers' images are verified against.

The supply chain is the perimeter. Every control in this article is a statement about which stage of the chain you trust, and the estates that get container security right are the ones that can say it plainly: we pin the base, we scan at build and on schedule, we sign at the pipeline, we verify at admission, we confine at the pod, and we detect at the node — and here's who owns each of those sentences.


References

  1. Aqua Security — "Trivy documentation": container, filesystem, and SBOM scanning, including offline vulnerability-database mode for air-gapped environments. Trivy Documentation, current.
  2. Anchore — "Grype documentation": vulnerability matching for containers and SBOMs. Grype Documentation, current.
  3. Sigstore — "Sigstore documentation": cosign keyless signing with Fulcio and Rekor, and verification with certificate-identity constraints. Sigstore Documentation, current.
  4. Kyverno — "Kyverno documentation": image verification policies and Pod Security admission control in Kubernetes. Kyverno Documentation, current.
  5. Tetragon — "Tetragon documentation": eBPF-based runtime security with policy-driven probes; Falco — "Falco documentation": rule-based syscall monitoring. Tetragon / Falco Documentation, current.
  6. NIST — SP 800-190 "Application Container Security Guide": container security guidance covering build, registry, and runtime hardening. NIST, current.
← Back to Articles ← Previous: CI/CD Pipelines for Infrastructure and Configuration Next: Load Balancing Architecture →