Kubernetes Security Best Practices: Harden Your Cluster
Security should be built into every layer of your Kubernetes deployment.
1. Pod Security Standards
Baseline Standards
apiVersion: v1
kind: Namespace
metadata:
name: secure-ns
labels:
pod-security.kubernetes.io/enforce: baseline
pod-security.kubernetes.io/warn: restrictedSecurity Context
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
fsGroup: 2000
containers:
- name: app
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL2. Network Policies
Default deny all traffic:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress3. RBAC Best Practices
- Use least privilege principle
- Avoid cluster-admin for applications
- Create service accounts per application
- Regular access audits
# Read-only access
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: read-only
rules:
- apiGroups: [""]
resources: ["*"]
verbs: ["get", "list", "watch"]4. Secrets Management
Don’t use ConfigMaps for secrets
Enable encryption at rest
# Encryption config
apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
- resources:
- secrets
providers:
- aescbc:
keys:
- name: key1
secret: <base64-encoded-key>5. Image Security
# Use specific tags, not :latest
image: nginx:1.21.0
# Use digest for production
image: nginx@sha256:abc123...Scan images for vulnerabilities:
trivy image nginx:1.21.06. Resource Limits
Prevent resource exhaustion attacks:
resources:
limits:
cpu: "500m"
memory: "256Mi"
requests:
cpu: "100m"
memory: "128Mi"7. API Server Security
- Enable audit logging
- Use HTTPS
- Disable anonymous authentication
- Enable RBAC
8. etcd Security
- Enable TLS for client/server communication
- Encrypt data at rest
- Regular backups
- Restrict network access
9. Node Security
- Regular OS updates
- Minimal base images
- Use CIS benchmarks
- Enable AppArmor/SELinux
# Check CIS compliance
kube-bench run --targets node10. Runtime Security
- Use Falco for threat detection
- Monitor for anomalies
- Implement admission controllers
# OPA Gatekeeper example
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: require-owner
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Namespace"]
parameters:
labels: ["owner"]Security Checklist
- Enable RBAC
- Configure NetworkPolicies
- Set Pod Security Standards
- Use security contexts
- Scan images
- Enable audit logging
- Encrypt secrets
- Regular updates
Practice Security
Security is the focus of CKS certification. Practice at Sailor.sh.