StackPractices
intermediate By Mathias Paulenko

Container Security Baseline Template

A baseline template for hardening container images, runtimes, and orchestration configurations across environments.

Overview

A Container Security Baseline defines the minimum security configuration that every container image, runtime, and workload must satisfy before it reaches production. It turns a vague “secure our containers” requirement into concrete, checkable controls: which base images are allowed, which security contexts are mandatory, which network flows are permitted, and how each rule gets enforced.

The template below is organized into four control areas — image build, runtime, orchestration, and exception handling — plus a deployment checklist you can attach to pull requests or release gates. Every row states the baseline and how to verify it, so the document works both as a policy statement and as an audit worksheet. Teams that already maintain a network segmentation policy can treat the networking rows here as the workload-level counterpart to that document.

When to Use

  • Setting up a new container platform or Kubernetes cluster.
  • Onboarding a new service or development team.
  • Preparing for a security audit or compliance review.
  • Responding to a container escape or image compromise.
  • Standardizing security controls across CI/CD and production.
  • Reconciling baselines after an acquisition or a platform migration.

Prerequisites

  • A container registry with access control and audit logging enabled.
  • A vulnerability scanner integrated with CI or the registry, such as Trivy, Grype, or a cloud-native scanner.
  • A Kubernetes cluster (1.25 or later recommended) with RBAC and NetworkPolicy support enabled.
  • Named owners: the platform team owns cluster controls, the security team approves policy and exceptions, and service teams own workload compliance.
  • A register — even a spreadsheet — for tracking exceptions, their owner, and their expiry date.

Solution

Template

Copy this template into your security handbook and adapt the values in each row. The Baseline column states the required configuration; the Verification column describes how to prove it during review or in CI. Pair it with the CI/CD pipeline security template when you document the build-side gates.

1. Image Build Requirements

RequirementBaselineVerification
Base imageMinimal, vendor-supported, or distroless images onlyApproved image list scanned in CI
Image sizeNo dev tools, shells, or package managers in the final layerdocker image inspect + Dockerfile review
VulnerabilitiesNo critical or high CVEs in production imagesScanner gate fails the build
SecretsNo credentials, tokens, or keys in any image layerLayer history review + secret scanning
ProvenanceImage signed, SBOM attached as attestationcosign verify + cosign verify-attestation
UpdatesImages rebuilt at least monthly to pick up base patchesScheduled CI job
TaggingImmutable version tags; latest never deployed to productionDeployment manifest check

2. Runtime Security Baseline

ControlBaselineEnforcement
Non-root userrunAsNonRoot: true, runAsUser above 10000Pod Security Admission, restricted profile
Read-only root filesystemreadOnlyRootFilesystem: true on every containerSecurity context / admission check
No privileged modeprivileged never set to truePod Security Admission (restricted) or a policy engine
Resource limitsCPU and memory requests and limits set per containerLimitRange defaults + policy check
Seccomp profileRuntimeDefault, or an approved custom profileSecurity context (restricted requires it)
AppArmor / SELinuxEnforcing profile applied on all nodesNode configuration
Capabilitiesdrop: ["ALL"]; at most NET_BIND_SERVICE added backSecurity context (restricted requires it)
Privilege escalationallowPrivilegeEscalation: falseSecurity context (restricted requires it)
Host namespaceshostPID, hostIPC, and hostNetwork all disabledbaseline profile blocks them
Host path volumesNo hostPath mounts without an approved exceptionbaseline profile blocks them

3. Orchestration Baseline

AreaBaselineTool / Resource
Pod Security Admissionrestricted enforced, enforce-version pinned to the cluster versionNamespace labels
RBACLeast-privilege roles scoped per namespace, no cluster-wide admin for workloadsKubernetes RBAC — see the RBAC policy template
Network policyDefault-deny, with flows explicitly allowed per workloadNetworkPolicy
Admission controlPolicy engine rejects non-compliant podsKyverno or OPA Gatekeeper
SecretsStored in an external vault or KMS, synced into the clusterVault / External Secrets Operator
Audit loggingAPI server audit log and container stdout collection enabledKubernetes audit policy
Node isolationSensitive workloads scheduled onto dedicated node poolsTaints / tolerations

4. Deployment Checklist

  • Image scanned with no critical or high vulnerabilities.
  • SBOM generated and the image signed at build time.
  • Container runs as non-root with a read-only root filesystem.
  • Privileged mode and host namespaces are disabled.
  • allowPrivilegeEscalation: false, drop: ["ALL"], and a seccomp profile set.
  • CPU and memory requests and limits configured.
  • Network policy restricts ingress and egress.
  • Secrets mounted from an external vault, not environment variables.
  • RBAC role is least-privilege and scoped to the namespace.
  • Pod Security Admission labels applied to the namespace.
  • The owning team can name every exception that applies to the workload.

5. Exception and Risk Acceptance

Not every workload can meet every control on day one. Exceptions are a managed escape valve, not a backdoor: each one needs an ID, an approver, a compensating control, and an expiry date. A common convention is a maximum lifetime of 90 days, renewable once after a fresh risk review.

Exception IDDescriptionRiskApproved ByExpirationCompensating Control
CS-001<describe the deviation>Medium<role, e.g. platform lead><YYYY-MM-DD><what reduces the risk>
CS-002<describe the deviation>High<role, e.g. CISO><YYYY-MM-DD><what reduces the risk>

How to Roll Out the Baseline

The fastest way to break production is to flip every namespace to Enforce on day one. Roll the baseline out in stages so teams can see violations, fix them, and then lock the door:

Baseline rollout loop — audit the fleet to list violations, warn workloads in Audit mode, let owning teams fix their manifests, enforce rejection of non-compliant pods, then keep rescanning and reviewing exceptions, which feeds back into the audit stage
  1. Audit. Run the scanner and the policy engine in report-only mode and count the violations per namespace. That violation count is your rollout plan.
  2. Warn. Set Pod Security Admission to warn/audit and Kyverno to Audit so developers see warnings without being blocked.
  3. Fix. Give each owning team its violation list and a deadline. Most failures are missing securityContext fields and resource limits — easy fixes, high volume.
  4. Enforce. Switch namespaces to Enforce, starting with the ones that already pass. Keep enforce-version pinned to a Kubernetes version so a cluster upgrade doesn’t silently tighten the rules.
  5. Maintain. Rescan images continuously, review open exceptions quarterly, and re-audit after every Kubernetes minor upgrade.

Explanation

Containers share the host kernel, so a single misconfigured workload can compromise the whole node it runs on. The baseline layers its controls to shrink that blast radius: image requirements stop vulnerable code from shipping, runtime restrictions limit what a container is allowed to do even when compromised, and orchestration policies apply those rules uniformly across every team and namespace.

The key design decision is where enforcement happens. A scanner in CI catches problems before an image exists in the registry, but it can’t stop someone from deploying a privileged pod by hand. Admission-time enforcement — Pod Security Admission plus a policy engine — closes that gap by checking every workload spec against the baseline at the API boundary. Treat the two as complements: CI gates for supply-chain artifacts, admission control for workload configuration.

Exceptions deserve the same rigor as the controls themselves. An exception register with an expiry date forces an explicit conversation about risk instead of letting one-off workarounds fossilize into permanent configuration. When an exception expires, the workload either gets fixed or the risk owner renews it after a fresh review.

There’s a real operational cost: admission checks add a small latency to every deployment, and strict security contexts occasionally break workloads that implicitly relied on writable filesystems or extra capabilities. That’s exactly what the staged rollout above is for — surface those cases in Audit mode and fix them before Enforce makes the failure loud.

Enforcement Examples

Enforcing pod security with Pod Security Admission

Pod Security Standards are the built-in Kubernetes admission profiles: privileged (no restrictions), baseline (blocks known privilege escalations), and restricted (current pod hardening best practices). Labeling a namespace turns them on without any external tooling:

# namespace-pod-security.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: production
  labels:
    pod-security.kubernetes.io/enforce: baseline
    pod-security.kubernetes.io/enforce-version: v1.31
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/audit-version: v1.31
    pod-security.kubernetes.io/warn: restricted
    pod-security.kubernetes.io/warn-version: v1.31

This configuration enforces baseline while warning and auditing at restricted, which is the recommended middle step during rollout. Pin the -version labels to an explicit Kubernetes version; latest silently changes meaning when the cluster upgrades.

Kyverno cluster policies for custom rules

Pod Security Admission covers the standard security-context checks. Kyverno adds what PSS can’t express: registry allow-lists, required labels, resource quotas per workload, or organization-specific naming rules. These policies enforce the non-root, no-privileged, and resource-limit rows of the baseline:

# kyverno-enforce-non-root.yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-non-root-user
spec:
  validationFailureAction: Enforce
  rules:
    - name: check-runAsNonRoot
      match:
        resources:
          kinds:
            - Pod
      validate:
        message: "Containers must run as non-root user (UID > 10000)"
        pattern:
          spec:
            containers:
              - securityContext:
                  runAsNonRoot: true
                  runAsUser: ">10000"

---
# kyverno-disallow-privileged.yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: disallow-privileged-containers
spec:
  validationFailureAction: Enforce
  rules:
    - name: reject-privileged
      match:
        resources:
          kinds:
            - Pod
      validate:
        message: "Privileged containers are not allowed"
        pattern:
          spec:
            containers:
              - =(securityContext):
                  =(privileged): false

---
# kyverno-require-resources.yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-cpu-memory-resources
spec:
  validationFailureAction: Enforce
  rules:
    - name: check-resources
      match:
        resources:
          kinds:
            - Pod
      validate:
        message: "CPU and memory requests and limits are required"
        pattern:
          spec:
            containers:
              - resources:
                  requests:
                    memory: "?*"
                    cpu: "?*"
                  limits:
                    memory: "?*"
                    cpu: "?*"

Three details matter here. First, privileged is a YAML boolean — write false, not the string "false", or the policy won’t match the field the way you expect. Second, the =(...) conditional anchor means “check this only if the field exists”: pods that simply omit securityContext.privileged already run unprivileged, and a plain privileged: false pattern would wrongly reject them. Third, ">10000" is Kyverno’s numeric comparison syntax, not a literal string — it evaluates runAsUser as a number. The resource policy now requires both requests and limits; checking only limits leaves schedulability unmanaged.

Default-deny networking with NetworkPolicy

Start from denying everything, then open only the flows each workload needs. The default-deny-all policy below applies to every pod in the production namespace; the two following policies whitelist frontend-to-backend traffic and DNS egress:

# default-deny-all.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
  namespace: production
spec:
  podSelector: {}
  policyTypes:
    - Ingress
    - Egress

---
# allow-frontend-to-backend.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-frontend-to-backend
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: backend
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: frontend
      ports:
        - protocol: TCP
          port: 8080

---
# allow-dns-egress.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-dns-egress
  namespace: production
spec:
  podSelector: {}
  policyTypes:
    - Egress
  egress:
    - to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: kube-system
          podSelector:
            matchLabels:
              k8s-app: kube-dns
      ports:
        - protocol: UDP
          port: 53
        - protocol: TCP
          port: 53

NetworkPolicies are additive per pod: once any policy selects a pod, every allowed flow must be declared in some policy. Forgetting the DNS egress rule is the most common cause of “network policy broke my app” incidents — name resolution fails silently before any other traffic can run.

Signing Images and Attesting the SBOM

Sign images at build time and verify them before deployment. The sequence below generates a key pair once, signs the image digest, attaches a CycloneDX SBOM as an attestation, and verifies both:

#!/bin/bash
set -euo pipefail

# Generate a key pair once; store cosign.key in a vault, never in the repo
cosign generate-key-pair

# Sign by digest, not by tag — tags can move between sign and deploy
IMAGE="registry.example.com/myapp@sha256:0123abcd..."
cosign sign --key cosign.key "$IMAGE"

# Attach an SBOM as a CycloneDX attestation
syft "$IMAGE" -o cyclonedx-json > sbom.json
cosign attest --key cosign.key \
  --predicate sbom.json \
  --type cyclonedx \
  "$IMAGE"

# Verify the signature before deployment
cosign verify --key cosign.pub "$IMAGE"

# Verify the SBOM attestation
cosign verify-attestation --key cosign.pub \
  --type cyclonedx \
  "$IMAGE" | jq -r '.payload' | base64 -d | jq .

The private key is the weak point of this whole setup. A cosign.key file in a CI workspace — or worse, committed to the repository — gives anyone who reads it the ability to sign images as your team. Prefer one of these instead of a raw key file:

  • Keyless signing with the CI platform’s OIDC identity (GitHub Actions, GitLab CI). Cosign gets a short-lived certificate from Fulcio and there’s no private key to protect at all.
  • A KMS URI such as gcpkms://, awskms://, or azurekms://, where the key material never leaves the KMS and signing is an API call.
  • A Kubernetes Secret or vault-backed mount if you must use a key pair, with rotation handled like any other credential.

Whichever option you choose, sign by digest. A mutable tag like v1.2.3 can be re-pointed between the moment you sign and the moment someone deploys, and the signature would still verify against the new, unreviewed image.

Managing Secrets and Registry Credentials

The baseline forbids long-lived credentials in environment variables and image layers. External Secrets Operator syncs secrets from a vault or cloud KMS into Kubernetes on a refresh interval, so a rotated registry token reaches the cluster without anyone re-deploying:

# external-secret-registry.yaml
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: registry-pull-secret
  namespace: production
spec:
  refreshInterval: 1h
  secretStoreRef:
    name: vault-backend
    kind: ClusterSecretStore
  target:
    template:
      type: kubernetes.io/dockerconfigjson
      data:
        .dockerconfigjson: "{{ .dockerconfig | toString }}"
  data:
    - secretKey: dockerconfig
      remoteRef:
        key: registry/credentials
        property: dockerconfigjson

The same pattern covers application secrets: keep the material in the external store, declare only the sync mapping in the cluster, and set refreshInterval to match the rotation period of the credential.

Variants

  • Docker-only baseline: the image and runtime sections alone, for teams running Docker without Kubernetes.
  • Kubernetes hardening checklist: only the orchestration rows plus the admission examples.
  • Serverless container baseline: for AWS Fargate or Google Cloud Run, where the platform owns the node controls and your scope shrinks to the image and workload config.
  • High-compliance baseline: adds FIPS-validated crypto, STIG-aligned hardening, or PCI-DSS evidence collection.
  • Developer laptop baseline: reduced checks for Docker Desktop and local builds, so developers catch violations before CI does.

What Works

  • Make the baseline mandatory through CI/CD gates and admission controllers, not through documentation alone.
  • Use distroless or scratch-based images so there’s less to patch and less to exploit.
  • Scan images continuously — new CVEs appear against images you built weeks ago.
  • Rotate registry credentials and signing keys on the same schedule as other secrets.
  • Monitor runtime behavior; a hardened image can still run a compromised process.
  • Version-control the policies themselves and review changes like application code.
  • Enforce with restricted Pod Security Admission where workloads tolerate it, and fall back to baseline plus Kyverno rules where they don’t.
  • Review the exception register on a fixed cadence and let expired exceptions block deployments.
  • Keep a short “why” paragraph in the template itself — teams comply faster when they understand the blast radius each control reduces.

Common Mistakes

  • Running containers as root because the base image defaults to it.
  • Embedding secrets in image layers or passing them as environment variables.
  • Pulling images from unverified public registries without pinning digests.
  • Scanning only the latest tag while older deployed versions drift unscanned.
  • Allowing unrestricted egress from every pod.
  • Checking privileged: false as a plain Kyverno pattern — without the =() anchor it rejects pods that simply omit the field.
  • Enabling Enforce in every namespace at once instead of staging through Audit.
  • Leaving enforce-version at latest so a cluster upgrade silently changes what is required.
  • Treating exceptions as permanent; without expiry dates they accumulate into shadow policy.
  • Relying only on image scanning and skipping runtime and admission controls entirely.

Measuring Baseline Compliance

A baseline you can’t measure is a suggestion. Track a small set of numbers and review them quarterly:

MetricWhat it tells youTarget
Namespaces at EnforceRollout progress100% of in-scope namespaces
Admission denials per weekViolations being attemptedTrending down after rollout
Open exceptionsAccumulated accepted riskBounded, all unexpired
Production images with critical CVEsScanning and rebuild healthZero older than 7 days
Workloads missing requests/limitsResource hygieneZero

See Also

Frequently Asked Questions

What is the difference between an image scanner and a runtime security tool?

An image scanner checks static image layers for known vulnerabilities and misconfiguration. A runtime tool watches the container while it executes and flags suspicious behavior — unexpected processes, network connections, or file writes. You need both: scanning stops bad artifacts from deploying, runtime detection catches what slips through or appears after deployment.

Should we use a privileged init container?

Avoid it. If a one-time setup genuinely needs elevated privileges, run it as a dedicated job with restricted RBAC and audit logging, and record it as a baseline exception with an expiry date.

How do we enforce the baseline automatically?

Combine CI/CD gates for the build side — scanning, signing, SBOM — with admission-time checks for the workload side. Pod Security Admission covers the standard security contexts with no extra components; Kyverno or OPA Gatekeeper adds custom rules for registries, labels, and resources.

What is the difference between Pod Security Standards and Kyverno policies?

Pod Security Standards are built-in Kubernetes admission profiles (privileged, baseline, restricted) that check a fixed list of security-context fields. Kyverno is a policy engine that can enforce the same checks plus custom rules on images, labels, resources, and anything else in the object spec. Use PSS for the standard controls and Kyverno for organization-specific rules.

How often should we rebuild and rescan container images?

Rebuild at least monthly to pick up base-image patches; critical services benefit from weekly rebuilds. A scheduled CI job that bumps the base tag, rebuilds, scans, and deploys on success keeps images current without manual effort:

# GitHub Actions weekly rebuild
name: Weekly Image Rebuild
on:
  schedule:
    - cron: "0 2 * * 1"
jobs:
  rebuild:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Build and scan
        run: |
          docker build -t myapp:latest .
          trivy image --exit-code 1 --severity HIGH,CRITICAL myapp:latest
What happens to workloads that cannot comply with the baseline?

They go through the exception process: document the deviation, assign a risk owner and a compensating control, and set an expiry date. When the exception expires, the workload gets remediated or the risk owner renews it after review. Workloads that never need the control should prompt you to reconsider the control's scope, not to grow the exception list.

Does the baseline apply to Windows containers?

Partially. Several restricted controls — allowPrivilegeEscalation, capabilities, seccomp, runAsNonRoot — are Linux-only checks that Kubernetes skips for Windows pods. On Windows nodes, enforce the equivalent controls through the Windows security context fields and HostProcess restrictions instead.