The issue opens pre-filled with this page title and URL.
This lesson teaches you to reduce what an image contains and to control what enters the cluster: minimal images, pinning by digest, SBOM, allowed registries, static analysis of Dockerfiles and manifests, and verification of the platform's binaries. It is aimed at anyone preparing the CKS (Certified Kubernetes Security Specialist) or the KCSA (Kubernetes and Cloud Native Security Associate). According to the official CKS curriculum, supply chain security accounts for 20% of the exam.
The official curriculum describes skills and imposes no tool: it only cites Kubesec and KubeLinter as examples for static analysis. The tools in this lesson are therefore interchangeable means.
Map the supply chain of an image and name the possible attack at each link
Reduce the footprint of an image with a multi-stage build and a distroless base
Pin an image by its digest and check what the node really runs
Generate an SBOM with Syft and rescan it without the image
Refuse an image coming from an unauthorised registry
Analyse a Dockerfile and a manifest before applying them
Verify a platform binary before installing it
Prerequisites
A Kubernetes cluster and kubectl configured
Docker basics: building an image with a Dockerfile
The notion of CVE (a known, numbered security flaw)
What is an image's supply chain?
The supply chain of a container image covers its whole journey before deployment, from the source code to the registry. Each link has its own security control, as the diagram shows: look, from left to right, at which control applies at which stage.
An attack can target any link. The table connects each link to what an attacker tries there and to the control from the diagram that answers it.
Link
Possible attack
Control
Source code
a malicious dependency enters the project
dependency control
Build
the build is hijacked and produces a tampered artifact
artifact control
Image
it ships known flaws
scan
Registry
the image is modified in transit, or the registry authenticates nobody
signature
Cluster
an unverified image is accepted
verification at admission
Swipe to see more
An image that works can therefore contain critical CVEs or have been tampered with: "it starts" proves nothing about its security.
1. Minimising the base image footprint
An image's footprint is everything it contains. Reducing it removes risk instead of adding detection: a package absent from the image generates no alert, needs no update and gives no lever to anyone who manages to run code in the container.
Why lightweight images reduce the attack surface
An image shipping apt, bash, curl and system tools offers an attacker running inside the container as many levers. A distroless image contains only the runtime and your binary. The table ranks common bases by attack surface.
Image type
Size
Attack surface
Use case
ubuntu:22.04
~70 MB
High (shell, apt, utils)
Development
alpine:3.19
~7 MB
Moderate (BusyBox shell)
General use
gcr.io/distroless/static
~2 MB
Minimal (no shell)
Go, static binaries
gcr.io/distroless/base
~20 MB
Very low (glibc only)
C, C++, Java
scratch
0 MB
Minimal on the base image side (security still depends on the shipped binary)
Fully static binaries
Swipe to see more
Multi-stage build: compiling without shipping the tools
A multi-stage build compiles in a full "build" image and copies only the final binary into a minimal image. Both bases are pinned by tag and digest: the tag says what you wanted, and the digest (the SHA-256 fingerprint of the image content) guarantees what you got.
Dockerfile
# Stage 1: compilation (full image)
FROM golang:1.27.4@sha256:5e8afd493a7124a8586e134d9b532731161d4b9becf9dee5a5956b107426f93d AS builder
WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 go build -o myapp .
# Stage 2: minimal final image (distroless)
FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab
COPY --from=builder /app/myapp /myapp
USER nonroot:nonroot
ENTRYPOINT ["/myapp"]
On distroless images, the :nonroot tag runs the container as UID 65532 instead of root. It is the principle of least privilege applied to the image itself: take a :nonroot variant when one exists, or explicitly declare an unprivileged user.
Image good practices
These rules answer a single question: is the image you deploy today identical to the one you tested yesterday? A tag is a pointer that the registry can reassign without your manifest changing. A digest is the hash of the content: it changes as soon as the content changes. Hence the hierarchy: latest guarantees nothing, a version tag guarantees an intent, a digest guarantees the content.
Freeze the version: nginx:1.31.3 rather than nginx:latest, because an update can introduce CVEs.
Add the digest without removing the tag: nginx:1.31.3@sha256:8541484afbc9c8a5a8a99b379568ebbc957f658583ec9448fc43104229c03cf8. The tag stays readable, the digest commits the content.
Do not install debuggers (gdb, strace, tcpdump) in production images.
Clean the cache in the same RUN: apt-get install -y curl && rm -rf /var/lib/apt/lists/*.
# Recommended: tag AND digest, readable and immutable
FROM nginx:1.31.3@sha256:8541484afbc9c8a5a8a99b379568ebbc957f658583ec9448fc43104229c03cf8
# ❌ to ban: latest is not reproducible
FROM nginx:latest
The second FROM, marked # ❌, is a counter-example: with latest, two builds made at different dates can produce two different images.
Checking that the declared digest is the one the node runs
Writing nginx@sha256:… in a Deployment is not enough: a digest of the right shape, copied from elsewhere, points to another image, or to none at all. The source of truth is the image the node actually resolved. The kubelet, the Kubernetes agent on each node, reports it in status.containerStatuses[].imageID of every Pod. This field comes from the container runtime and its format depends on it: the sha256:… part is what you compare.
This command lists, for each Pod of the chaine namespace (the lab's), the resolved image:
The digest on each line must be identical to the one written in the Deployment's image field. After pinning the Deployment, also check that all replicas are running, here with kubectl -n chaine rollout status deployment/pinned-app: an immutable reference that prevents the Pod from starting is not an improvement.
If you reuse the digest read from imageID, pinning does not change the image that runs: you freeze that precise content, not another version. In return, a digest never receives a security fix by itself: it is refreshed when you rebuild the image and carry over its new digest.
2. Scanning for vulnerabilities
An image scan looks for known CVEs in the image's packages, with a scanner such as Grype or Trivy. This gesture has its own lesson: Scanning Kubernetes images details the commands, the exit codes and the limits of each tool. To read the scores, see Understanding CVE, CVSS and EPSS.
Keep the limit in mind here: an image without known CVEs is not a trustworthy image. It may have been tampered with, come from a compromised source or carry malicious code that no database references. The scan answers a precise question, "which known flaws does this image contain", and it replaces neither the signature, which establishes integrity and origin (Signing and verifying an image with Cosign), nor the admission policy, which decides what enters the cluster.
3. Generating and using an SBOM
An SBOM (Software Bill of Materials) is the exhaustive inventory of an image's components: system packages, libraries, versions and licences. It is the ingredient list of your software: it can be archived, then rescanned months later without needing the image, as soon as a new CVE is published.
The file produced is a CycloneDX JSON: its components list gives, for each component, its name, its version and its purl identifier, and grype sbom: rescans that list without touching the image. The example image nginx:1.25.3 is deliberately old, so that the scan finds CVEs. See the full SBOM guide for the SPDX and CycloneDX formats and CI/CD integration.
4. Limiting the allowed registries
To accept only images coming from approved registries, Kubernetes does nothing by itself: it is an admission control that refuses the creation of the Pod. Admission is the stage where the Kubernetes API submits every object to checks before storing it.
The usual route is a policy engine that you install, Kyverno or Gatekeeper. Kubernetes can also enforce, without installing anything, rules written in CEL (Common Expression Language, a small expression language): ValidatingAdmissionPolicy has been stable since 1.30.
Here is the policy with Kyverno 1.19.1 (chart 3.9.1), which serves the policies.kyverno.io/v1 API. Two elements carry the behaviour. validationActions: [Deny] refuses the creation instead of producing a mere report. The CEL expression walks, with all(...), the three container lists of a Pod: containers, initContainers (started before the others) and ephemeralContainers (added afterwards, to debug). An expression limited to spec.containers lets through a Pod whose only initContainer comes from elsewhere.
message: "Only images from registry.example.com are allowed, init containers and ephemeral containers included."
The pods/ephemeralcontainers subresource is the one kubectl debug uses to attach an ephemeral container to an existing Pod: without it in resourceRules, the policy never sees that addition. A kubectl run on a Docker Hub image then returns:
Output
Error from server: admission webhook "vpol.validate.kyverno.svc-fail" denied the request: Policy restrict-registries failed: Only images from registry.example.com are allowed, init containers and ephemeral containers included.
The same refusal, word for word, hits a Pod whose initContainer comes from Docker Hub and a kubectl debug aimed at an otherwise compliant Pod. Beware: matchConstraints only targets Pods here. A Deployment passes, then its Pod is refused, and the error message shows up in the ReplicaSet, not in the Deployment.
For the same rule with Gatekeeper, and to understand what each engine does with the request, see Kyverno, Gatekeeper (in French) and Admission controllers (in French).
5. Analysing Dockerfiles and manifests before applying them
Scanning an image looks for known vulnerabilities in packages. It says nothing about a Dockerfile that runs as root or a manifest that declares privileged: true: the packages can be perfectly up to date, the deployment stays dangerous. Static analysis reads the configuration files before they produce anything.
Analysing a Dockerfile with trivy config
trivy config <directory> analyses the configuration files it finds, Dockerfiles included. It is the same tool as for images, used upstream: an image scan measures what an image contains, trivy config measures what its recipe promises. Each finding carries an identifier of the form DS-0002, a severity, a title and a Resolution section that says what to write.
Terminal window
trivyconfiginventaire/
With Trivy 0.74.0, on an inventaire/ directory whose Dockerfile builds and runs but has never been hardened, you typically get a failure on findings of this family: DS-0001 (floating latest tag), DS-0002 (the image runs as root), DS-0004 (port 22 exposed), DS-0026 (no HEALTHCHECK) and DS-0029 (apt-get without --no-install-recommends). Trivy adds rules with every version: look for these findings by their identifier rather than demanding "zero findings", which would turn red by itself when a new rule ships.
The fixes are made without changing what the application does. DS-0001 is fixed by pinning the FROM by tag and digest, as in the first section, and DS-0004 by removing EXPOSE 22. The other three findings are fixed with three lines to place in your Dockerfile, after the FROM: a package installation without recommendations (DS-0029), a health check (DS-0026) and a non-root user (DS-0002). This block is an excerpt, not a complete file: adapt the port and the command of the health check to your application, and the user name to your image (node exists in the official Node.js images).
Do not change technology to make a finding disappear, and do not delete the Dockerfile: the analysis would fall silent without the problem being fixed. A linter such as Hadolint (in French) does the same analysis work without building the image.
Analysing a manifest with kube-linter and kubesec
The CKS curriculum (v1.37) cites two tools as examples in the line "Perform static analysis of user workloads and container images (e.g. Kubesec, KubeLinter)". They do not do the same job. On a deliberately weak manifest, carrying privileged: true, runAsUser: 0, an image on latest and a hostPath on the root, the difference shows immediately:
Tool
What it returns
On the weak manifest
Once hardened
kube-linter 0.8.3
a list of named defects, with the remediation
8 errors, exit 1
2 errors left
kubesec 2.14.2
a numeric score and a verdict
-30 points, exit 2
+13, "Passed", exit 0
Swipe to see more
Terminal window
kube-linterlintdeployment.yaml
kubesecscandeployment.yaml
Remember the difference in use: kube-linter lists, which helps fix; kubesec scores, which helps set a threshold in continuous integration.
These two tools read a file, not the cluster: they see nothing of what has already been applied, which remains the job of an admission controller. Two neighbouring tools do the same work from another angle: kube-score (in French), designed for continuous integration, and Polaris (in French), which watches a live cluster continuously.
6. Verifying the platform binaries
The supply chain does not stop at images: the kubectl you install on an administration workstation is part of it. The CKS curriculum asks you to verify platform binaries before deploying.
Kubernetes publishes the checksum of each binary next to the binary, under the same name suffixed .sha256. The check takes three commands, and sha256sum --check does all the work:
It is the exit code that counts, not the message. Measured on the 1.37.0 binary: 0 when the file is intact, 1 as soon as it is tampered with, and a single byte added to a 61 MB binary is enough to flip it. In a script, test this code rather than looking for the word OK in the output.
The sum is published in the same place as the binary: it detects a tampered download, not a compromised site, which would publish a modified binary with its own sum. Only a signature, verified with a key published elsewhere, answers that risk. The signing and verification gesture is detailed, for an image, in Signing and verifying an image with Cosign.
Full supply chain workflow
Here is the complete cycle, in the order the controls chain together: each step produces what the next one verifies. The registry digest only exists once the image is pushed, which is why pinning and signing come after the push.
Build with a minimal base image (distroless or alpine) and a multi-stage build
Analyse the Dockerfile and the manifests: trivy config ., kube-linter lint
Scan the image before the push: grype myapp:1.0.0 --fail-on high
Generate the SBOM: syft myapp:1.0.0 -o cyclonedx-json
Push to a private, controlled artifact repository, an approved internal registry
Pin by digest: resolve the digest with crane digest (Crane, a command-line tool that queries a registry), then reference the image by that @sha256:… in the manifests
Verify and limit at admission: Kyverno or Gatekeeper policy
Troubleshooting
The cluster does here what it was asked to do, and it is the configuration that is the problem. The most deceptive case is the second row: nothing fails, the creation succeeds and the expected control never took place. If your chain seems too quiet, start there.
Symptom
Likely cause
Solution
The Deployment's digest differs from the Pods' imageID
Digest copied from a source other than the node
Reread status.containerStatuses[].imageID and take that digest
A Pod with an external initContainer is created despite the policy
CEL expression limited to spec.containers
Also walk initContainers and ephemeralContainers
trivy config reports a DS-… finding after the fix
Rule added by a new Trivy version
Look for the targeted identifiers, not a total of zero
latest images in production
Permissive tag convention
Add an admission policy that refuses latest, for example with Kyverno
Swipe to see more
Put it into practice
Two links of the chain, each validated on the state of the cluster and not on the commands typed. In the first lab, you pin a Deployment on the digest the node actually resolved: the last test compares the declared digest with the runtime's, and both replicas must run. In the second, you run trivy config on a Dockerfile refused on five points and you fix the five findings, rerun by their identifier, without changing what the image does or deleting the file.
Key points
Minimal images: distroless then alpine then ubuntu, multi-stage build; scratch reduces the base footprint but security depends on the shipped binary.
A tag is mutable, a digest commits the content: pin, then check in status.containerStatuses[].imageID that the declared digest is the one the node runs.
Scanning is not enough: an image without CVEs can still be compromised, so complete it with signing and admission.
An SBOM is an inventory that you rescan without the image.
Refusing an unauthorised registry is the job of an admission control, with a CEL expression covering containers, initContainers and ephemeralContainers.
trivy config analyses a Dockerfile, kube-linter lists the defects of a manifest and kubesec scores it; kubesec returns 2 on failure, so test for non-zero.
A platform binary is verified with sha256sum --check, and the exit code is what counts.
Test your knowledge
The questions cover footprint reduction, the digest, the SBOM, admission and static analysis. Several ask you to tell two neighbouring notions apart: tag and digest, scan and signature, static analysis and admission control.
Knowledge check
Check what you have learned with this interactive quiz
7 questions
8 min
70% to pass
How it works
The timer starts when you click Start
Multiple choice, true/false and short answer questions
You can move between questions
Detailed results are shown at the end
Starts the quiz and the timer
⏱️--:--
0 / 7
Review
(0/0)
--:--
0%
0Correct
0To review
0:00Time
-Level
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.