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.
Core Concepts
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: 5432The 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:
- ALLNon-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:
| Method | Security level | Use case |
|---|---|---|
| Kubernetes Secrets | Basic | Development |
| Vault integration | High | Production |
| Cloud provider solutions | High | Cloud-native |
| Sealed Secrets | High | GitOps |
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.0Whichever 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: OnFailurePair 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: WARNINGShip audit logs and runtime alerts somewhere an attacker who owns the cluster cannot erase them.
Decision Framework
| Situation | Recommendation |
|---|---|
| New cluster, limited time | Default-deny network policies, Restricted pod security, per-workload service accounts — in that order |
| Secrets currently in plain Kubernetes Secrets | Move production to an external store (Vault or cloud KMS-backed); enable etcd encryption today |
| GitOps workflow | Sealed Secrets or an external-secrets operator so repos never hold plaintext |
| Compliance-driven environment | Audit logging at RequestResponse for sensitive resources, shipped off-cluster |
| Multi-tenant cluster | All of the above plus namespace isolation treated as a hard boundary and reviewed quarterly |
Implementation Checklist
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
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.