Skip to main content

Kubernetes Security Best Practices:

 

Kubernetes Security Best Practices: A Comprehensive Guide

📅 Published: September 2026
⏱️ Estimated Reading Time: 18 minutes
🏷️ Tags: Kubernetes Security, Cluster Security, Pod Security, RBAC, Network Policies


Introduction: The Shared Responsibility Model

Kubernetes security is a shared responsibility. The cloud provider secures the infrastructure (hardware, network, hypervisor), while you are responsible for securing the cluster itself, the workloads running on it, and the data it stores.

Think of Kubernetes security as layers of an onion. No single security control is sufficient. You need defense in depth—multiple layers of protection that work together to keep your cluster safe.

This guide covers the essential security controls for every Kubernetes cluster:

  • Authentication & Authorization: Who can access the cluster and what they can do

  • Pod Security: How pods run and what they can access

  • Network Security: What traffic is allowed

  • Image Security: Ensuring containers are safe

  • Cluster Security: Securing the control plane and nodes


Part 1: Authentication and Authorization

1. Use RBAC (Role-Based Access Control)

RBAC is the primary mechanism for controlling access to the Kubernetes API.

Best Practices:

  • Enable RBAC: Ensure RBAC is enabled (default on most clusters)

  • Least Privilege: Grant only the permissions needed

  • Use Groups: Assign permissions to groups, not individual users

  • Regular Audits: Review RBAC configurations periodically

Example RBAC:

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

Common RBAC Roles:

RolePermissionsUse Case
ViewerRead-only access to all resourcesAuditors, monitoring
DeveloperCreate/update pods, services, configmapsApplication developers
OperatorFull access to a specific namespaceTeam leads
AdminFull access to all namespacesCluster administrators
Cluster AdminFull access to everythingPlatform engineers

2. Service Accounts and Pod Identities

Service accounts provide identity for pods.

Best Practices:

  • Disable Default Service Account Auto-mounting:

    yaml
    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: default
    automountServiceAccountToken: false
  • Create Dedicated Service Accounts:

    yaml
    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: my-app-sa
  • Use Workload Identity:

    • AWS: IAM Roles for Service Accounts (IRSA)

    • GCP: Workload Identity

    • Azure: Workload Identity

3. Use OIDC for External Authentication

yaml
# OIDC configuration (kube-apiserver)
--oidc-issuer-url=https://accounts.google.com
--oidc-client-id=kubernetes
--oidc-username-claim=email
--oidc-groups-claim=groups

Part 2: Pod Security

1. Pod Security Standards

Kubernetes provides three built-in Pod Security Standards:

StandardDescriptionUse Case
PrivilegedNo restrictionsSystem components, CI/CD runners
BaselineMinimal restrictions, prevents known privilege escalationsGeneral purpose applications
RestrictedHeavily restricted, follows hardening best practicesHighly sensitive workloads

Enforce with Pod Security Admission:

yaml
apiVersion: v1
kind: Namespace
metadata:
  name: production
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/enforce-version: latest
    pod-security.kubernetes.io/warn: baseline
    pod-security.kubernetes.io/audit: restricted

2. SecurityContext

SecurityContext configures security settings at the pod or container level.

yaml
apiVersion: v1
kind: Pod
metadata:
  name: secure-pod
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
    runAsGroup: 1000
    seccompProfile:
      type: RuntimeDefault
  containers:
  - name: app
    image: myapp:latest
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop: ["ALL"]
        add: ["NET_BIND_SERVICE"]

Key SecurityContext Settings:

SettingPurpose
runAsNonRoot: truePrevent running as root
runAsUserSet non-root user ID
readOnlyRootFilesystem: trueMake root filesystem read-only
allowPrivilegeEscalation: falsePrevent gaining more privileges
capabilities.drop: ["ALL"]Drop all Linux capabilities
seccompProfile.type: RuntimeDefaultRestrict system calls

3. Resource Limits

Set resource limits to prevent DoS attacks.

yaml
resources:
  requests:
    memory: "256Mi"
    cpu: "250m"
  limits:
    memory: "512Mi"
    cpu: "500m"

Part 3: Network Security

1. Network Policies

Network Policies control traffic flow between pods and endpoints. By default, pods can communicate freely. Use Network Policies to restrict this.

Default Deny All:

yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-all
  namespace: default
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress

Allow Only from Specific Namespace:

yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-from-monitoring
spec:
  podSelector:
    matchLabels:
      app: backend
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          name: monitoring
    ports:
    - protocol: TCP
      port: 9090

2. Service Mesh Security

Use a service mesh (Istio, Linkerd) for mTLS encryption between services.

mTLS Configuration (Istio):

yaml
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: default
spec:
  mtls:
    mode: STRICT

Part 4: Image Security

1. Use Minimal Base Images

Choose minimal base images to reduce attack surface.

Base ImageSizeUse Case
DistrolessMinimalProduction
AlpineVery smallGeneral purpose
SlimSmallBalanced
FullLargeDevelopment

2. Scan Images for Vulnerabilities

Scan all container images before deployment.

Trivy:

bash
trivy image --severity HIGH,CRITICAL myapp:latest

GitHub Actions with Trivy:

yaml
- name: Scan image
  uses: aquasecurity/trivy-action@master
  with:
    image-ref: myapp:${{ github.sha }}
    format: 'sarif'
    output: 'trivy-results.sarif'
    severity: 'CRITICAL,HIGH'

3. Use Trusted Registries

  • Use trusted image registries (Docker Hub official images, ECR, GCR)

  • Enable registry authentication for private registries

  • Use image signing (Cosign, Notary)


Part 5: Cluster Security

1. Upgrade Kubernetes Regularly

Keep your Kubernetes cluster updated with security patches.

bash
# Check available updates
kubectl get nodes -o wide
# Or use your cloud provider's update mechanism

2. Secure kube-apiserver

  • Use TLS for all communication

  • Enable audit logging

  • Restrict access to the API server

  • Use OIDC for external authentication

3. etcd Security

  • Encrypt etcd data at rest

  • Restrict access to etcd (only for kube-apiserver)

  • Backup etcd regularly

4. Use Private Clusters

  • Use private clusters (VPC only, no public endpoints)

  • Use network policies to restrict access

  • Use VPN or private connectivity for management


Security Checklist

Authentication & Authorization

  • RBAC enabled and properly configured

  • Service accounts have minimal permissions

  • OIDC or other authentication configured

  • Audit logs enabled

Pod Security

  • Pod Security Standards enforced

  • SecurityContext configured for all pods

  • Resource limits set

  • Non-root user enforced

Network Security

  • Network Policies implemented

  • Default deny all policy applied

  • Ingress/egress traffic restricted

  • Service mesh for mTLS (if applicable)

Image Security

  • Minimal base images used

  • Images scanned for vulnerabilities

  • Image signing enabled

  • Trusted registries used

Cluster Security

  • Kubernetes version up to date

  • etcd encrypted

  • Private cluster network configured

  • Regular security audits performed

Monitoring & Logging

  • Cluster monitoring enabled

  • Audit logging configured

  • Security alerts configured

  • Regular security reviews


Common Kubernetes Security Mistakes

MistakeRiskMitigation
Running as rootContainer can access host resourcesUse runAsNonRoot: true
No resource limitsDoS attacksSet CPU/memory limits
Public endpointsExposed to internetUse private clusters or network policies
No network policiesPods can communicate freelyApply default deny policy
Using latest tagUnpredictable versionsUse specific image tags
No image scanningVulnerable images deployedIntegrate scanning in CI/CD
Too permissive RBACExcessive permissionsApply least privilege
No audit loggingNo visibility into attacksEnable audit logging

Summary

LayerKey Controls
AuthenticationRBAC, Service Accounts, OIDC
Pod SecurityPod Security Standards, SecurityContext
NetworkNetwork Policies, Service Mesh
ImagesMinimal images, Scanning, Signing
ClusterUpgrades, etcd encryption, Private clusters
MonitoringAudit logs, Monitoring, Alerts

Learn More

Practice Kubernetes security with hands-on exercises in our interactive labs:
https://devops.trainwithsky.com

Comments

Popular posts from this blog

🌐 Holographic Communications & 6G: The Future of Immersive Connectivity

  🌐 Holographic Communications & 6G: The Future of Immersive Connectivity 🚀 Introduction As the world moves towards 6G , a revolutionary technology is set to redefine digital interactions: Holographic Communications . Imagine real-time, 3D holographic video calls, immersive remote collaboration, and lifelike virtual experiences —all powered by ultra-fast, ultra-low-latency 6G networks . This topic explores Holographic Communications , its impact on various industries, key enabling technologies, and how 6G will bring this futuristic concept to reality . Shape Your Future with AI & Infinite Knowledge...!! Want to Generate Text-to-Voice, Images & Videos? http://www.ai.skyinfinitetech.com Read In-Depth Tech & Self-Improvement Blogs http://www.skyinfinitetech.com Watch Life-Changing Videos on YouTube https://www.youtube.com/@SkyInfinite-Learning Transform Your Skills, Business & Productivity – Join Us Today! 🔍 1. What is Holographic Communication? Hologr...

How to Use SKY TTS: The Complete, Step-by-Step Guide for 2025

 What is SKY TTS? SKY TTS  is a free, next-generation  AI audio creation platform  that brings together high-quality  Text-to-Speech ,  Speech-to-Text , and a full suite of professional  audio editing tools  in one seamless experience. Our vision is simple — to make advanced audio technology  free, accessible, and effortless  for everyone. From creators and educators to podcasters, developers, and businesses, SKY TTS helps users produce  studio-grade voice content  without expensive software or technical skills. With support for  70+ languages, natural voices, audio enhancement, waveform generation, and batch automation , SKY TTS has become a trusted all-in-one toolkit for modern digital audio workflows. Why Choose SKY TTS? Instant Conversion:  Enjoy rapid text-to-speech generation, even with large documents. Advanced Voice Settings:   Adjust speed, pitch, and style for a personalized listening experience. Multi-...

📊 Monitoring & Logging in Kubernetes – Tools like Prometheus, Grafana, and Fluentd

  Monitoring & Logging in Kubernetes – Tools like Prometheus, Grafana, and Fluentd Monitoring and logging are essential for maintaining a healthy and well-performing Kubernetes cluster. In this guide, we’ll cover why monitoring is important, key monitoring tools like Prometheus and Grafana, and logging tools like Fluentd to help you gain visibility into your cluster’s performance and logs. Shape Your Future with AI & Infinite Knowledge...!! Want to Generate Text-to-Voice, Images & Videos? http://www.ai.skyinfinitetech.com Read In-Depth Tech & Self-Improvement Blogs http://www.skyinfinitetech.com Watch Life-Changing Videos on YouTube https://www.youtube.com/@SkyInfinite-Learning Transform Your Skills, Business & Productivity – Join Us Today! 🚀 Introduction In today’s fast-paced cloud-native environment, Kubernetes has emerged as the de-facto container orchestration platform. But deploying and managing applications in Kubernetes is just half the ba...