KubernetesIntermediate

Kubernetes Security Best Practices: A Comprehensive Guide

8 min read

TL;DR

Learn essential security best practices for Kubernetes clusters, including RBAC, network policies, pod security, and secrets management.

Kubernetes Security Best Practices: A Comprehensive Guide

Executive Summary

Kubernetes ships with permissive defaults: pods can talk to each other, containers often run as root, and service accounts carry more power than the workloads need. This guide works through the control layers that close those gaps — RBAC, network policies, pod security standards, secrets management, image security, audit logging, and runtime detection — with working configuration for each. By the end you will be able to decide which controls to apply first, how to verify they are actually enforced, and where the residual risk honestly sits.

Why This Matters

A compromised container should be an incident, not a breach. In an unhardened cluster it becomes a breach quickly: the attacker reads the pod's service account token, queries the API server, lists secrets in the namespace, and moves laterally to every pod that accepts traffic. Each control in this guide exists to break one step of that chain. The cost of skipping them is not theoretical — it is the difference between restarting one pod and rotating every credential in the cluster.

Security is layers, not a single control Every layer assumes the one above it can fail. Identity RBAC · SA Admission Pod Security Network NetworkPolicy Runtime seccomp · AppArmor Secrets + images sealed secrets · signed images only A namespace alone is not a boundary — the layers around it are what make it one.

Core Concepts

What each control actually stops Match the control to the attack, not to the checklist. RBAC Least privilege who can do what stops credential abuse POD SECURITY Restricted no privileged pods stops node escape NETWORKPOLICY Default deny allow-list only stops lateral movement One control per failure mode — a gap in any layer is a path an attacker will find.

RBAC: Least Privilege for Humans and Workloads

Role-Based Access Control decides who can do what to which resources. A Role grants verbs on resources inside one namespace; a RoleBinding attaches it to users, groups, or service accounts:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: production
  name: pod-reader
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "watch", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods
  namespace: production
subjects:
- kind: User
  name: jane
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io

Three disciplines make RBAC work. First, verbs and resources are always named explicitly — never wildcards, which quietly include resources added in future Kubernetes versions. Second, every workload gets its own service account with only the API access it genuinely needs; most need none, and for those, disable token automounting entirely. Third, cluster-admin bindings are treated like root shells: few, named, and reviewed on a schedule.

Network Policies: Default-Deny, Then Allow

By default every pod can reach every other pod. A NetworkPolicy selects pods and states exactly which traffic is allowed; anything not matched is denied once a policy selects the pod:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-network-policy
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
    ports:
    - protocol: TCP
      port: 8080
  egress:
  - to:
    - podSelector:
        matchLabels:
          app: database
    ports:
    - protocol: TCP
      port: 5432

The working pattern is a default-deny policy per namespace, then one allow policy per real communication path. Two caveats matter: policies are only enforced if your CNI implements them (verify — some do not), and egress rules must include DNS or you will break name resolution and misdiagnose it as an application bug.

Pod Security: Constrain What a Container Can Be

Pod Security Standards (Baseline and Restricted profiles, enforced through Pod Security Admission) reject pods that ask for dangerous privileges. The security context then sets the per-workload details:

apiVersion: v1
kind: Pod
metadata:
  name: secure-pod
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
    fsGroup: 2000
  containers:
  - name: app
    image: myapp:1.0
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop:
        - ALL

Non-root execution, a read-only root filesystem, no privilege escalation, and all capabilities dropped removes most container-escape and persistence techniques in one stanza. Apply the Restricted profile namespace by namespace — expect some workloads to need remediation, which is the point.

Secrets Management

Kubernetes Secrets are base64-encoded, not encrypted, and are readable by anyone with API access to them. They are a distribution mechanism, not a vault. Choose by environment:

MethodSecurity levelUse case
Kubernetes SecretsBasicDevelopment
Vault integrationHighProduction
Cloud provider solutionsHighCloud-native
Sealed SecretsHighGitOps

External systems inject secrets at runtime, scoped to the workload's identity:

apiVersion: v1
kind: ServiceAccount
metadata:
  name: vault-auth
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
spec:
  template:
    metadata:
      annotations:
        vault.hashicorp.com/agent-inject: "true"
        vault.hashicorp.com/agent-inject-secret-credentials: "database/creds/app"
    spec:
      serviceAccountName: vault-auth
      containers:
      - name: app
        image: myapp:1.0

Whichever store you choose: enable encryption at rest for etcd, rotate on a schedule and immediately on suspicion, and audit who reads secrets — reads are the exfiltration path.

Image Security: Scan, Sign, Minimise

Vulnerable images are the most common way known exploits enter a cluster. Scanning in CI and again on a schedule catches what was clean at build time and is not now:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: image-scanner
spec:
  schedule: "0 0 * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: trivy
            image: aquasec/trivy
            args:
            - image
            - --severity
            - HIGH,CRITICAL
            - myapp:1.0
          restartPolicy: OnFailure

Pair scanning with signing (cosign) and admission checks that only signed images from approved registries may run. Prefer minimal bases — distroless or slim images carry fewer packages, which means fewer vulnerabilities and less tooling for an attacker who does get in.

Audit Logging and Runtime Detection

Audit logs record who did what to the API server; policy controls the volume by resource sensitivity:

apiVersion: audit.k8s.io/v1
kind: Policy
metadata:
  name: audit-policy
rules:
- level: RequestResponse
  resources:
  - group: ""
    resources: ["secrets", "configmaps"]
- level: Metadata
  resources:
  - group: ""
    resources: ["pods", "services"]

Runtime security tools such as Falco watch syscalls inside running containers and flag behaviour no legitimate workload exhibits — a shell spawned in a production container is the canonical example:

apiVersion: v1
kind: ConfigMap
metadata:
  name: falco-rules
data:
  falco_rules.yaml: |
    - rule: Terminal shell in container
      desc: A shell was spawned by a pod in the cluster
      condition: container.id != host and proc.name = bash
      output: Shell opened in container (user=%user.name container=%container.name)
      priority: WARNING

Ship audit logs and runtime alerts somewhere an attacker who owns the cluster cannot erase them.

Decision Framework

SituationRecommendation
New cluster, limited timeDefault-deny network policies, Restricted pod security, per-workload service accounts — in that order
Secrets currently in plain Kubernetes SecretsMove production to an external store (Vault or cloud KMS-backed); enable etcd encryption today
GitOps workflowSealed Secrets or an external-secrets operator so repos never hold plaintext
Compliance-driven environmentAudit logging at RequestResponse for sensitive resources, shipped off-cluster
Multi-tenant clusterAll of the above plus namespace isolation treated as a hard boundary and reviewed quarterly

Where to spend the next security hour Fix the layer that is missing before polishing the one that exists. Can a pod run privileged? or reach any other pod? Pod Security restricted first NetworkPolicy default deny RBAC audit who is cluster-admin? If all three are in place, the next hour goes to image signing and secrets — not more policy.

Implementation Checklist

  • [ ] No wildcard verbs or resources in any Role or ClusterRole; cluster-admin bindings enumerated and justified
  • [ ] Default service account token automounting disabled for workloads that do not call the API
  • [ ] Default-deny NetworkPolicy in every namespace, with explicit allows per real traffic path
  • [ ] Pod Security Admission enforcing Restricted (or Baseline as an interim step) per namespace
  • [ ] All production containers run as non-root with capabilities dropped and read-only root filesystems where feasible
  • [ ] Secrets in an external store or sealed; etcd encryption at rest enabled; rotation schedule documented
  • [ ] Images scanned in CI and on a schedule; admission restricted to approved registries
  • [ ] Audit logs and runtime alerts shipped off-cluster with alerting on secret reads and shell spawns
  • Trade-offs

    Every control here costs operability. Restricted pod security breaks workloads that casually assume root or a writable filesystem. Default-deny networking turns missing rules into outages. External secrets add a dependency whose failure can block deployments. The honest posture is to adopt the controls in order of blast-radius reduction and budget real remediation time — security that the team routes around is worse than a smaller set they actually maintain.

    When Not to Use

  • Hand-rolled encryption or a custom secrets scheme: never. Use Vault, a cloud KMS-backed store, or Sealed Secrets — reviewed cryptography and key handling are the entire product.
  • Network policies as your only isolation: they are layer 3/4 controls enforced by the CNI. For hostile multi-tenancy, add separate node pools or clusters; a policy is not a hypervisor boundary.
  • A local, disposable dev cluster: full production controls on a kind/minikube sandbox slow learning and protect nothing. Apply the subset that mirrors production behaviour (RBAC shape, pod security) and skip the rest.
  • Conclusion

    Kubernetes security is layered containment: RBAC limits the API, network policies limit movement, pod security limits the container, external secrets limit credential exposure, and audit plus runtime detection limit how long an intruder stays invisible. Apply the layers in that order, verify enforcement rather than assuming it, and review access on a schedule — the cluster you secured last quarter drifts like any other system.

    Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.