smaple.tr
Kubernetes security

Kubernetes Security Guide: Container Hardening, RBAC, and Runtime Defense [2026]

Mehmet Kurtipek
July 1, 2026
12 min read
Kubernetes security
container security
RBAC
network policy
Falco
OPA Gatekeeper
supply chain security
runtime security

Over 70% of production container images contain at least one critical vulnerability. The dynamic nature of Kubernetes clusters — hundreds of microservices, thousands of pods, continuously changing network topology — makes traditional perimeter security inadequate. Each layer of the stack requires its own security controls: the image before it runs, the cluster when it's configured, the runtime when it executes, and the supply chain that produced the software.

This guide covers Kubernetes security from image hardening to zero-trust inter-service communication. By the end, you will have a security model that addresses image scanning, RBAC configuration, network segmentation, runtime threat detection, supply chain integrity, and the tools to implement each layer in production.

Container Image Security

Kubernetes security begins before a pod runs. The container image is the attack surface at rest — vulnerabilities in the image become vulnerabilities in production.

Image Scanning

Automated image scanning in CI/CD is the first layer of defense. Tools integrate at different points:

Trivy (Aqua Security): Fast, comprehensive scanner covering OS packages, language libraries, IaC misconfigurations, and secrets. The most common choice for CI/CD pipeline integration due to its speed and low false-positive rate.

Grype (Anchore): Similar scope to Trivy. Output format differences make it preferred in some organizations' reporting pipelines.

Snyk: Commercial scanner with strong developer tooling integration. Offers fix suggestions and license compliance checks in addition to vulnerability detection.

Scanning policy recommendation: block images with CRITICAL severity vulnerabilities from deploying to production. Flag HIGH severity for immediate remediation. Track MEDIUM and LOW to avoid alert fatigue. Integrate scanning into the pull request pipeline so vulnerabilities are caught before they reach the main branch.

Dockerfile Security Patterns

The Dockerfile itself determines the attack surface:

Non-root user: Running containers as root gives potential attackers host-level privilege escalation paths. Always specify a non-root USER in the Dockerfile.

Multi-stage builds: Build dependencies (compilers, build tools, test frameworks) should not appear in the final image. Multi-stage builds separate build environment from runtime image — the final stage contains only the compiled binary and its runtime dependencies.

Distroless base images: Google's distroless images contain only the runtime (Go binary, JVM, Node.js) without package managers, shells, or POSIX utilities. This eliminates the tooling that post-exploitation scripts depend on. Chainguard's hardened images take this further with zero-CVE base images under active maintenance.

No secrets in layers: Docker layer caching persists secrets added during build even if they're deleted in a later layer. Pass secrets via Docker BuildKit's --secret mount or environment variables at runtime, never baked into the image.

Kubernetes Security Model

RBAC Configuration

Kubernetes RBAC controls who can perform which operations on which resources. The principle of least privilege applies strictly: every ServiceAccount, user, and automation should have only the permissions required for its specific function.

Common RBAC misconfiguration patterns to avoid:

Overly permissive ClusterRoles: The cluster-admin ClusterRole grants full access to all resources across all namespaces. Binding this to a ServiceAccount used by a workload is a critical misconfiguration — if that pod is compromised, the attacker has full cluster control.

Wildcard permissions: Rules with verbs: ["*"] or resources: ["*"] violate least privilege. Enumerate specific verbs and resources.

Default ServiceAccount overuse: Kubernetes automatically mounts the default ServiceAccount token into pods unless disabled. Many applications do not need to call the Kubernetes API at all — set automountServiceAccountToken: false in the pod spec when not needed.

RBAC audit: Regularly review ClusterRoleBindings and RoleBindings for bindings to the cluster-admin role or wildcard permissions. Tools like kubectl-who-can and kube-audit automate this review.

NetworkPolicy: Micro-Segmentation

By default, Kubernetes allows all pod-to-pod communication within a cluster. A compromised pod can reach any other service on any port. NetworkPolicy implements micro-segmentation — explicit allow rules for ingress and egress, with implicit deny for unspecified traffic.

Default-deny pattern: Create a NetworkPolicy that denies all ingress and egress, then add explicit allow rules for necessary communication paths. This inverts the default posture from "allow everything" to "deny everything except what's explicitly allowed."

NetworkPolicy requires a CNI plugin that enforces policies — Calico, Cilium, and Weave Net enforce NetworkPolicy. The default Kubernetes CNI does not. Verify your CNI supports NetworkPolicy enforcement before deploying policies.

Pod Security Standards

Kubernetes 1.25 deprecated PodSecurityPolicy (PSP) and replaced it with Pod Security Standards (PSS), enforced via the built-in Pod Security Admission controller.

Three security levels:

Level Restrictions When to Use
Privileged None System components, CNI plugins
Baseline Prevents known privilege escalation vectors General application workloads
Restricted Strict security requirements Sensitive workloads, compliance environments

Apply the restricted level to application namespaces as the default. Apply baseline to infrastructure namespaces that need more flexibility. Apply privileged only to system namespaces (kube-system) where required.

Admission Controllers

Admission controllers validate and mutate API server requests before resources are created. They are the enforcement layer for cluster-wide security policies.

OPA Gatekeeper: Policy as code using Rego. Constraint Templates define policy logic; Constraints apply policies to specific resources with configuration. Gatekeeper's audit mode lets you detect existing violations without blocking new deployments — useful for rolling out new policies without disrupting running workloads.

Kyverno: YAML-native policy engine without Rego. Lower learning curve, native Kubernetes API integration, and built-in support for image signature verification (Cosign). Kyverno also supports generate policies — automatically creating companion resources (NetworkPolicy, ResourceQuota) when a new namespace is created.

Feature OPA Gatekeeper Kyverno
Policy language Rego YAML
Learning curve Steep Low
Mutation support Limited Comprehensive
Image verification External (Cosign) Native Cosign
Generate policies No Yes
Community library Extensive Growing

For most Kubernetes teams new to policy enforcement, Kyverno's lower learning curve and broader built-in capabilities make it the practical choice. Gatekeeper's Rego flexibility becomes an advantage in large multi-tenant environments with complex policy logic.

Supply Chain Security

Software supply chain attacks — compromising dependencies, build pipelines, or container registries to inject malicious code — have increased dramatically. Container ecosystems are a primary target.

Image Signing and Verification

Sigstore/Cosign: The open-source standard for container image signing. Cosign supports keyless signing (using OIDC identity from GitHub Actions, Google Workload Identity, or other OIDC providers) and traditional key-based signing. Signed images include attestations in the container registry — admission controllers can verify signatures before allowing image deployment.

Keyless signing with Cosign integrates naturally with CI/CD: GitHub Actions workflows sign images using the workflow's OIDC identity, creating a cryptographically verifiable link between the image and the pipeline that produced it.

SBOM (Software Bill of Materials)

An SBOM is a machine-readable inventory of every component in a software artifact. SBOM generation enables:

  • Vulnerability response: When a new CVE is published, query your SBOM inventory to immediately identify which images are affected
  • License compliance: Track open-source licenses across your entire software estate
  • Audit documentation: Demonstrate component provenance to regulators and customers

Syft (Anchore) and Trivy both generate SBOMs in SPDX and CycloneDX formats. Cosign's attach sbom command stores the SBOM as an OCI artifact alongside the image in the registry.

Supply Chain Security Controls

Control Tool Priority
Image scanning Trivy, Grype Critical
Image signing Cosign, Notation High
SBOM generation Syft, Trivy High
Dependency updates Dependabot, Renovate Medium
Provenance verification SLSA framework High

SLSA (Supply-chain Levels for Software Artifacts) provides a graduated framework for supply chain integrity. SLSA Level 2 (hermetic, reproducible builds with provenance) is achievable for most teams with current tooling.

Runtime Security

Pre-deployment controls (image scanning, admission controllers) prevent known vulnerabilities and policy violations. Runtime security detects anomalous behavior in running containers.

Kubernetes Security with Falco

Falco (CNCF graduated project) monitors Linux kernel system calls and applies rules to detect suspicious behavior in running containers. Unlike file-based intrusion detection, Falco sees all syscall activity — process execution, network connections, file access, and privilege escalation attempts.

High-value Falco rules:

  • Shell spawned in container: Production containers should not spawn interactive shells. An unexpected shell is a strong indicator of attacker activity.
  • Sensitive file access: Access to /etc/shadow, /etc/passwd, or cloud credential files warrants immediate investigation.
  • Outbound connection to unexpected host: Containers making outbound connections to unknown IPs may indicate data exfiltration or C2 communication.
  • Privilege escalation: setuid and capability changes should be rare and expected. Unexpected privilege escalation is a critical alert.

Falco alerts can be routed to SIEM, PagerDuty, Slack, or any system via its output plugin framework. Integration with SOAR platforms enables automated response — isolating pods or revoking service account tokens automatically on high-confidence alerts.

eBPF-Based Security with Cilium Tetragon

Cilium Tetragon uses eBPF (extended Berkeley Packet Filter) for kernel-level visibility and policy enforcement. Unlike Falco, which detects and alerts, Tetragon can block policy violations in real time without userspace overhead.

Tetragon's TracePolicy resources define enforcement actions at the kernel level — process creation, file access, and network connections can be allowed, logged, or killed based on policy. This in-kernel enforcement eliminates the window between detection and response that exists with external monitoring tools.

Secret Management

Kubernetes Secrets are base64-encoded, not encrypted, by default. A user with access to kubectl get secret or direct etcd access can read all Secrets in plaintext. Production workloads require stronger secret management.

HashiCorp Vault

Vault is the enterprise standard for secrets management at scale. Key capabilities for Kubernetes:

Dynamic secrets: Vault generates database credentials, cloud provider tokens, and PKI certificates on demand with automatic expiration. There are no static credentials to leak — a compromised service gets credentials that expire in hours or minutes.

Vault Agent Injector: Sidecar injection pattern that authenticates with Vault using Kubernetes ServiceAccount tokens and delivers secrets to the pod filesystem at startup. Applications read secrets from files — no Vault SDK required.

Transit secrets engine: Encryption-as-a-service. Applications send plaintext to Vault and receive ciphertext, with Vault managing the encryption keys. This ensures keys are never exposed to application code.

External Secrets Operator

External Secrets Operator (ESO) synchronizes secrets from external providers (AWS Secrets Manager, Azure Key Vault, GCP Secret Manager, HashiCorp Vault) into Kubernetes Secrets on a configurable refresh interval.

ESO enables centralized secret management with existing cloud-native secret stores rather than introducing a new service. For teams already using AWS Secrets Manager or Azure Key Vault, ESO provides Kubernetes integration without migrating to a new platform.

Kubernetes Security with the CIS Benchmark

The CIS Kubernetes Benchmark is the most comprehensive reference for cluster hardening configuration. It covers control plane components (API Server, etcd, Controller Manager, Scheduler), worker node configuration (kubelet, kube-proxy), RBAC policies, and audit logging.

kube-bench (Aqua Security) automates CIS Benchmark checks, producing a pass/fail report with remediation guidance for each finding. Run kube-bench as part of cluster provisioning validation and on a scheduled basis to detect configuration drift.

Automated scanning tools:

Tool Scope Mode
kube-bench CIS Benchmark CLI / CronJob
kubeaudit Security audit CLI
Kubescape NSA/CISA + CIS CLI / Operator
Polaris Best practices CLI / Dashboard

Zero-Trust Pod-to-Pod Communication

Zero-trust networking in Kubernetes means no implicit trust between services, even within the cluster. Every service-to-service communication is authenticated and encrypted.

Service Mesh with mTLS

Istio and Cilium service meshes implement mutual TLS (mTLS) for all pod-to-pod communication. In mTLS, both the client and server authenticate each other using certificates managed automatically by the mesh control plane.

Istio PeerAuthentication with mode: STRICT enforces mTLS across a namespace. No plain-text service communication is permitted. Combined with AuthorizationPolicy, fine-grained access control limits which services can call which endpoints with which HTTP methods.

Cilium provides native eBPF-based network policy enforcement with an optional service mesh layer. For teams that prioritize performance, Cilium's kernel-level packet processing offers lower overhead than Istio's envoy proxy sidecar model.

Zero-Trust Security Checklist

  • Apply mTLS for all inter-service communication
  • Create a dedicated ServiceAccount for each deployment (no shared accounts)
  • Default-deny NetworkPolicy with explicit allow rules
  • RBAC with least-privilege for all ServiceAccounts
  • Route audit logs to a centralized SIEM
  • Restrict cloud resource access via workload identity (IAM Roles for Service Accounts on AWS/GCP)

Vulnerability Management Lifecycle

Container vulnerability management is a continuous process, not a one-time scan.

Discover: Automated image scanning on every CI/CD build. Scheduled rescanning of running images — a vulnerability-free image today may be vulnerable tomorrow when a new CVE is published.

Prioritize: CVSS score alone is insufficient for prioritization. Combine CVSS with EPSS (Exploit Prediction Scoring System) to estimate real-world exploitability and with exposure analysis (internet-facing vs. internal) to rank remediation effort.

Remediate: Define SLAs by severity. A common baseline: CRITICAL in 24 hours, HIGH in 7 days, MEDIUM in 30 days, LOW in the next sprint cycle. Automated base image update pipelines (Renovate, Dependabot) reduce manual effort for the majority of remediation work.

Verify: Rescan after patching. Penetration testing validates that remediations are effective and that no new vulnerabilities were introduced.

Conclusion

Kubernetes security requires defense in depth — controls at every layer, from the build pipeline to the running container. No single tool or configuration change addresses the full threat surface.

The practical starting point for most teams:

  1. Foundational hygiene: Pod Security Standards enforced at namespace level, RBAC minimization, default-deny NetworkPolicy
  2. Automated scanning: Image scanning in CI/CD, admission controller enforcement (Kyverno or Gatekeeper)
  3. Runtime detection: Falco for anomaly detection and alerting

Adding supply chain controls (image signing, SBOM), Vault for secret management, and service mesh mTLS completes the security posture for production-grade environments.

Security and deployment velocity are not in opposition. DevSecOps practices — integrating security controls into the CI/CD pipeline — enable both. The goal is to make the secure path the easy path, so that developers don't have to choose between shipping fast and shipping securely.

Related Articles

August 11, 2026

MLOps Guide: Taking Machine Learning Models to Production [2026]

87% of machine learning models built by data science teams never reach production. The models work — they pass cross-validation, they score well on holdout sets, they demonstrate genuine predictive value. The problem is not the modeling. The problem is everything that happens between a notebook experiment and a reliable, monitored, production system. MLOps is the discipline that closes that gap. This guide covers the full MLOps stack: maturity levels, tooling choices (MLflow, DVC, Kubeflow

Read More: MLOps Guide: Taking Machine Learning Models to Production [2026]
August 10, 2026

LLM Fine-Tuning Guide: Custom Model Training with LoRA and QLoRA [2026]

General-purpose LLMs are impressive. They can write code, summarize documents, answer questions, and translate between languages with reasonable accuracy. But "reasonable" is not good enough when your application requires consistent output format, domain-specific terminology, a particular tone, or behavior that the base model was never trained to exhibit. That gap is where fine-tuning matters. Fine-tuning updates a model's weights on your specific data, changing how the model behaves — not

Read More: LLM Fine-Tuning Guide: Custom Model Training with LoRA and QLoRA [2026]
August 9, 2026

Computer Vision Applications: Object Detection, OCR, and Industrial AI [2026]

Computer vision has moved well past the research phase. The models are trained, the frameworks are mature, the hardware is accessible, and the use cases are generating measurable returns. What was a specialized capability requiring deep expertise in 2018 is now deployable infrastructure — if you know which component to reach for and where the real complexity lives. This guide covers computer vision applications across industrial, medical, logistics, and document processing domains. It expl

Read More: Computer Vision Applications: Object Detection, OCR, and Industrial AI [2026]