Kubernetes Security Best Practices
In this article
- Background: Why Kubernetes Security Is Hard
- How to Secure the Cluster Infrastructure
- Securing the Software Supply Chain
- Workload Hardening: Pods and Containers
- Access Control and Authentication
- Network Security and Policies
- Monitoring, Auditing, and Incident Response
- Common Mistakes and Misconceptions
- Frequently Asked Questions
- Conclusion
Kubernetes security best practices center on defense in depth: securing the cluster from the image registry down to the runtime, applying least-privilege access everywhere, and continuously auditing configuration. This article outlines the essential practices for hardening a Kubernetes deployment, covering everything from cluster setup to workload isolation.
Background: Why Kubernetes Security Is Hard
Kubernetes is a distributed system with many moving parts: API server, etcd, kubelet, container runtime, network proxies, and controllers. Each component is a potential attack surface. Misconfigurations—like running containers as root or exposing the API server to the internet—are common and often exploited. The CIS Kubernetes Benchmark provides a checklist of security recommendations, but it's not a substitute for understanding the underlying principles.
How to Secure the Cluster Infrastructure
The foundation of Kubernetes security starts with the infrastructure itself.
- Control plane access: Restrict access to the API server and etcd. Use private networks, firewalls, and TLS for all communication. Never expose the API server to the public internet without strong authentication and network policies.
- Etcd encryption: Enable etcd encryption at rest. Secrets stored in etcd are base64-encoded by default, not encrypted—anyone with read access to etcd can read them.
- Node hardening: Keep nodes patched, disable unnecessary services, and use a minimal host OS. Consider using a dedicated container-optimized OS like Flatcar or GKE's COS.
- Network segmentation: Use network policies to restrict east-west traffic. By default, all pods can communicate with each other. Define policies that allow only required traffic.
Securing the Software Supply Chain
Your images are the code that runs in the cluster. If they contain vulnerabilities, the cluster is at risk.
- Use minimal base images: Start from scratch or distroless images. Avoid heavyweight images with unnecessary tools.
- Scan images: Integrate an image scanner (e.g., Trivy, Grype, or Clair) into your CI/CD pipeline. Scan for known vulnerabilities and fail the build if critical ones exist.
- Sign images: Use cosign or similar to sign images. Verify signatures before deployment to prevent tampering.
- Pin image tags: Avoid using
latesttags. Use immutable tags based on the digest (e.g.,myimage@sha256:...) to ensure you know exactly what's running.
Workload Hardening: Pods and Containers
Even with secure infrastructure, a compromised container can be a beachhead. Apply these practices to every pod.
- Run as non-root: Set
securityContext.runAsNonRoot: trueand specify a non-root user. Most images can run as a non-root user with minimal effort. - Read-only root filesystem: Set
readOnlyRootFilesystem: trueand mount volumes for any writes. This limits what an attacker can modify. - Drop capabilities: Drop all capabilities and add back only what's needed. The default set of Linux capabilities is more than most applications require.
- Use seccomp and AppArmor: Apply seccomp profiles to restrict system calls. Kubernetes supports seccomp profiles per pod, and many runtimes have default profiles.
- Resource limits: Set CPU and memory limits to prevent a compromised container from exhausting node resources.
Access Control and Authentication
Kubernetes RBAC is powerful but often misconfigured. Follow least privilege.
- Use RBAC: Define roles and role bindings that grant only the permissions needed. Avoid cluster-admin except for a few administrators.
- Use service accounts: Each application should have its own service account, not the default. Grant it only the permissions it needs.
- Enable OIDC or other external authentication: Integrate with your corporate identity provider. Disable static password and token files.
- Rotate credentials: Regularly rotate service account tokens, kubeconfigs, and certificates. Use short-lived tokens where possible.
Network Security and Policies
Network policies are the first line of defense against lateral movement.
- Default deny: Create a default deny-all network policy. Then add policies that allow specific traffic.
- Use namespace labels: Apply labels to namespaces and use them in policy selectors to make policies easier to manage.
- Encrypt traffic: Use mTLS (e.g., with Istio or Linkerd) to encrypt pod-to-pod traffic. This prevents eavesdropping even if an attacker gets on the network.
Monitoring, Auditing, and Incident Response
You can't secure what you can't see.
- Enable audit logging: Turn on the Kubernetes audit log. Capture API requests, including metadata like user, source IP, and response status.
- Monitor runtime: Use tools like Falco to detect anomalous behavior at the runtime level (e.g., shell inside a container, unexpected system calls).
- Set up alerts: Alert on suspicious events: repeated failed logins, unexpected network connections, or changes to RBAC policies.
- Have a response plan: Prepare runbooks for common incidents: compromised container, API server exposure, etcd compromise. Test them regularly.
Common Mistakes and Misconceptions
Even experienced teams make these errors.
- Assuming namespaces are security boundaries: Namespaces are for organization, not isolation. An attacker who gains access to one namespace can often move to others.
- Ignoring the default service account: The default service account in each namespace has no permissions, but many applications mount it unnecessarily. Disable automounting for the default account.
- Not disabling the insecure port: Older Kubernetes versions had an insecure port (8080) on the API server. Ensure it's disabled (it's off by default in modern versions).
- Forgetting about secrets in environment variables: Secrets mounted as files are safer than environment variables, which can be exposed in the pod spec or logs.
Frequently Asked Questions
Is Kubernetes secure by default?
No. Kubernetes is designed to be flexible, and many security features are opt-in. For example, network policies are not enforced unless you install a CNI that supports them and define policies. Similarly, pod security policies (now deprecated) had to be explicitly configured. You must actively harden your cluster.
What is the difference between a pod security policy and a pod security admission?
Pod Security Policies (PSP) were deprecated in Kubernetes 1.21 and removed in 1.25. They were replaced by Pod Security Admission (PSA), which is a built-in admission controller that applies predefined security standards (privileged, baseline, restricted) to pods based on labels. PSA is simpler and easier to manage.
How do I secure secrets in Kubernetes?
Use Kubernetes Secrets, but understand they are only base64-encoded by default. Enable encryption at rest for etcd. For stronger security, use an external secrets manager like HashiCorp Vault or AWS Secrets Manager, and inject secrets as files or via CSI drivers. Never put secrets in environment variables or images.
Should I use a service mesh for security?
A service mesh like Istio or Linkerd provides mTLS, fine-grained authorization, and observability. It's a valuable addition, but it's not a replacement for network policies or RBAC. It adds complexity, so evaluate whether your use case justifies it.
What is the best way to handle RBAC for many teams?
Use namespaces per team and bind roles within those namespaces. Define roles with the minimum permissions needed for common tasks (e.g., deploy, view logs). Use groups from your identity provider to assign roles, rather than individual users. Regularly review role bindings to remove stale permissions.
Conclusion
Kubernetes security is a continuous process, not a one-time setup. Start with the basics: secure the control plane, use RBAC, harden workloads, and monitor activity. Then gradually add more layers like image signing, mTLS, and runtime detection. The effort pays off in reduced risk of a breach and faster recovery if one occurs.