Kubernetes Security Best Practices: How to Protect Your Containerized Applications
Eight practical ways to secure Kubernetes: container images, RBAC, network policies, pod security, secrets, monitoring and supply chain.
Kubernetes is the standard for container orchestration. In the Cloud Native Computing Foundation's 2023 annual survey, 84% of organizations were using or evaluating it¹. That popularity also makes Kubernetes an attractive target, and security now slows delivery: in Red Hat's 2024 State of Kubernetes Security report, 67% of respondents had delayed or slowed deployments because of security concerns².
The complexity of Kubernetes with multiple layers of components, networking, and access controls, securing a Kubernetes cluster requires a comprehensive approach that goes far beyond traditional security measures. A single misconfiguration can expose your entire infrastructure to attack.
This guide draws on hands-on work securing production Kubernetes on GKE and EKS, and focuses on the practices that separate secure deployments from vulnerable ones.
This guide presents the essential Kubernetes security best practices, and strategies to protect your containerized applications against external threats.
Why Kubernetes Security Matters
Attackers usually target misconfigurations, vulnerable container images, and weak access controls.
The shared responsibility model in Kubernetes adds another layer of complexity. While cloud providers like AWS and Google Cloud secure the underlying infrastructure, you're responsible for securing your applications, configurations, and data within the cluster.
Consider these numbers:
- In 2024, the average breach took 194 days to identify and cost $4.88 million³
- Malicious open source packages rose 156% year over year⁴
The good news is most Kubernetes security incidents are preventable with proper implementation of security best practices.
1. Secure Container Images from the Start
The first step begins before containers ever reach your Kubernetes cluster. Container images are the foundation of your applications, and vulnerable images can compromise your entire environment.
Container Image Security Best Practices:
Use Minimal Base Images: Choose minimal base images like Alpine Linux or Google's Distroless images to reduce attack surface. These images contain only essential components, eliminating unnecessary packages that could introduce vulnerabilities.
Implement Image Scanning:
- AWS: Amazon ECR Image Scanning for vulnerability detection
- Google Cloud: Artifact Registry Container Analysis API for security scanning
- Third-party tools: Integrate Trivy, Snyk, or Grype for advanced scanning capabilities
Keep Images Updated: Regularly update base images and dependencies to patch known vulnerabilities. Implement automated image rebuilding when security updates are available.
When deploying never Use 'latest' Tags: Always use specific version tags for production deployments. The 'latest' tag can introduce unexpected changes and security vulnerabilities.
Image Security Implementation:
# Example: Secure image specification
apiVersion: apps/v1
kind: Deployment
metadata:
name: secure-app
spec:
template:
spec:
containers:
- name: app
image: myapp:v1.2.3 # Specific version, not 'latest'
securityContext:
runAsNonRoot: true
runAsUser: 1000
readOnlyRootFilesystem: true
Key Metrics to Track on container images:
- Number of critical/high vulnerabilities in deployed images
- Time between vulnerability disclosure and image updates
- Percentage of images using specific version tags
2. Role-Based Access Control (RBAC)
Kubernetes RBAC is an important line of defense against unauthorized access to your Kubernetes cluster. Over-broad permissions turn one stolen credential into access to the whole cluster.
RBAC Implementation Strategy:
Principle of Least Privilege: Grant users and service accounts only the minimum permissions necessary to perform their functions. Start with restrictive permissions and expand as needed.
Namespace-Level Isolation: Use namespaces to create logical boundaries between applications and teams. Implement RBAC policies that restrict access to specific namespaces.
Service Account Management: Create dedicated service accounts for each application with specific, limited permissions. Avoid using the default service account for production workloads.
RBAC Configuration Example:
# Example: Restrictive RBAC policy
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: production
name: app-reader
rules:
- apiGroups: [""]
resources: ["pods", "services"]
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: app-reader-binding
namespace: production
subjects:
- kind: ServiceAccount
name: app-service-account
namespace: production
roleRef:
kind: Role
name: app-reader
apiGroup: rbac.authorization.k8s.io
RBAC Best Practices:
- Regularly audit RBAC permissions and remove unused access
- Implement break-glass procedures for emergency access
- Use tools like kubectl-who-can to analyze permissions
- Monitor RBAC events for suspicious activity
3. Network Policies for micro-segmentation
Network segmentation is critical for limiting the blast radius of security incidents. Kubernetes Network Policies provide fine-grained control over pod-to-pod communication.
Network Policy Implementation:
Default Deny All: Start with a default deny-all network policy and explicitly allow only necessary traffic. This approach ensures that new pods have no network access by default.
Ingress and Egress Controls: Define both ingress (incoming) and egress (outgoing) rules for comprehensive traffic control. Many organizations focus only on ingress rules, leaving egress traffic uncontrolled.
Label-Based Policies: Use Kubernetes labels to create dynamic and maintainable network policies that automatically apply to pods based on their characteristics.
Network Policy Example:
# Example: Restrictive network policy
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: web-app-netpol
namespace: production
spec:
podSelector:
matchLabels:
app: web-app
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
Network Policy Tools:
- Calico: Advanced network policy engine with enterprise features
- Cilium: eBPF-based networking with enhanced security capabilities
- AWS VPC CNI: Native AWS networking with security group integration
4. Pod Security Standards
Pod Security Standards (PSS) replace the deprecated Pod Security Policies, providing a simplified approach to enforcing security constraints on pods.
Pod Security Standards Implementation:
Security Levels:
- Privileged: Unrestricted policy for system-level workloads
- Baseline: Minimally restrictive policy preventing known escalations
- Restricted: Heavily restricted policy following current pod hardening best practices
Enforcement Modes:
- Enforce: Policy violations cause pod creation to fail immediately
- Audit: Policy violations are logged but pods are still created
- Warn: Policy violations trigger user-facing warnings
Pod Security Configuration:
# Example: Namespace with Pod Security Standards
apiVersion: v1
kind: Namespace
metadata:
name: secure-apps
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/audit: restricted
pod-security.kubernetes.io/warn: restricted
Security Context Best Practices:
- Run containers as non-root users
- Use read-only root filesystems
- Drop unnecessary Linux capabilities
- Disable privilege escalation
- Set resource limits and requests
5. Secure Secrets Management
Kubernetes Secrets provide a mechanism for storing sensitive information, but they require careful handling to maintain security.
Secrets Security Best Practices:
Encryption at Rest: Enable etcd encryption to protect secrets stored in the cluster database. Both AWS EKS and Google GKE support envelope encryption for enhanced security.
External Secrets Management: Consider using external secret management systems like:
- AWS: AWS Secrets Manager with External Secrets Operator
- Google Cloud: Secret Manager with CSI Secret Store driver
- HashiCorp Vault: Enterprise-grade secret management
Least Privilege Access: Limit secret access to only the pods and service accounts that require them. Use RBAC to control secret access permissions.
External Secrets Implementation:
# Example: External Secrets Operator configuration
apiVersion: external-secrets.io/v1beta1
kind: SecretStore
metadata:
name: aws-secrets-manager
namespace: production
spec:
provider:
aws:
service: SecretsManager
region: us-west-2
auth:
secretRef:
accessKeyID:
name: aws-creds
key: access-key-id
secretAccessKey:
name: aws-creds
key: secret-access-key
Secret Rotation: Implement automated secret rotation to limit the impact of compromised credentials. Both AWS and Google Cloud provide automated rotation capabilities for their secret management services.
6. Monitoring and Logging
Observability is key for detecting and responding to security incidents in Kubernetes environments. Breaches took 194 days on average to identify in 2024³; good logging and alerting are how you shorten that.
Monitoring and Logging Strategy:
Audit Logging: Enable Kubernetes audit logging to track all API server requests. Configure appropriate audit policies to capture security-relevant events without overwhelming your logging infrastructure.
Container Runtime Security: Implement runtime security monitoring to detect anomalous behavior in running containers:
- Falco: Open-source runtime security monitoring
- AWS GuardDuty: Kubernetes protection for EKS clusters
- Google Cloud Security Command Center: Comprehensive security monitoring
Metrics and Alerting: Monitor key security metrics and configure alerting for suspicious activities:
- Failed authentication attempts
- Privilege escalation attempts
- Unusual network traffic patterns
- Resource usage anomalies
Monitoring Configuration Example:
# Example: Falco rule for detecting suspicious activity
- rule: Terminal shell in container
desc: A shell was used as the entrypoint/exec point into a container
condition: >
spawned_process and container and
shell_procs and proc.tty != 0 and
container_entrypoint
output: >
A shell was spawned in a container with an attached terminal
(user=%user.name container_id=%container.id image=%container.image.repository)
priority: NOTICE
7. Supply Chain Security
Supply chain attacks keep growing: Sonatype's 2024 State of the Software Supply Chain report found a 156% year-over-year increase in malicious open source packages⁴. Securing your software supply chain is critical for Kubernetes security.
Supply Chain Security Measures:
Software Bill of Materials (SBOM): Generate and maintain SBOMs for all container images to track dependencies and identify vulnerable components.
Image Signing and Verification: Implement container image signing using tools like Cosign and enforce signature verification in your Kubernetes clusters.
Admission Controllers: Use admission controllers to enforce security policies and prevent deployment of non-compliant resources:
- OPA Gatekeeper: Policy-based admission control
- Kyverno: Kubernetes-native policy management
- Falco Admission Controller: Runtime security policy enforcement
Admission Controller Example:
# Example: Gatekeeper constraint requiring image signatures
apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
name: requiredsignature
spec:
crd:
spec:
names:
kind: RequiredSignature
validation:
properties:
trustedKeys:
type: array
items:
type: string
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package requiredsignature
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
not has_valid_signature(container.image)
msg := sprintf("Container image %v must be signed", [container.image])
}
8. Regular Security Assessments and Updates
Kubernetes security is not a one-time implementation but an ongoing process requiring regular assessment and updates.
Security Assessment Practices:
Regular Penetration Testing: Conduct regular penetration testing of your Kubernetes environments to identify vulnerabilities and misconfigurations.
Compliance Scanning: Use tools like kube-bench to assess your cluster against CIS Kubernetes Benchmark standards.
Vulnerability Management: Implement automated vulnerability scanning and patching processes for both cluster components and container images.
Security Training: Provide regular security training for development and operations teams to ensure they understand current threats and best practices.
Assessment Tools:
- kube-bench: CIS Kubernetes Benchmark assessment
- kube-hunter: Kubernetes cluster penetration testing
- kubesec: Static analysis of Kubernetes manifests
- Polaris: Configuration validation and best practices
Conclusion: Building a Secure Kubernetes Future
Kubernetes security requires a layered approach that addresses every aspect of your containerized environment. From secure container images to robust monitoring, each component plays a crucial role in your overall security posture.
The key to successful Kubernetes security is understanding that it's not a destination but a journey. Threats evolve, new vulnerabilities are discovered, and best practices continue to develop.
Organizations that treat security as an ongoing process, rather than a one-time implementation, will be best positioned to protect their containerized applications.
Remember these fundamental principles:
- Security starts with container images - scan, update, and harden from the beginning
- Implement defense in depth - use multiple security layers that work together
- Principle of least privilege - grant minimal necessary permissions
- Continuous monitoring - visibility is essential for threat detection
- Regular assessment - test and validate your security controls
Applied together, these practices turn a vulnerable cluster into a secure, resilient platform. The investment in Kubernetes security pays dividends through reduced risk, improved compliance, and increased confidence in your containerized infrastructure.
Ready to Secure Your Kubernetes Environment?
Strong Kubernetes security can feel overwhelming, but you don't have to work it out alone. Black Castle reviews your clusters, ranks the gaps and helps your engineers close them, in a way that also stands up in a SOC 2 or HIPAA audit.
Book a free call. In 30 minutes we look at where you stand and name your top three gaps. No sales pitch.
References:
- Cloud Native Computing Foundation. (2024). CNCF Annual Survey 2023. https://www.cncf.io/reports/cncf-annual-survey-2023/
- Red Hat. (2024). Kubernetes adoption, security, and market trends report 2024. https://www.redhat.com/en/resources/kubernetes-adoption-security-market-trends-overview
- IBM Security. (2024). Cost of a Data Breach Report 2024. https://www.ibm.com/reports/data-breach
- Sonatype. (2024). 10th Annual State of the Software Supply Chain Report. https://www.sonatype.com/press-releases/sonatypes-10th-annual-state-of-the-software-supply-chain-report
About the author: William Pispico Ferreira is the founder of Black Castle and holds the Certified Kubernetes Security Specialist (CKS) and Certified Kubernetes Administrator (CKA) certifications.