Kubernetes logo with title β€œPod Security Contexts and Network Policies” displayed on a clean diagram background"

πŸ” Kubernetes Security: Pod Security Contexts & Network Policies

In this guide, we’re stepping into real-world Kubernetes security. Not theory β€” actual hands-on controls that protect your workloads.

What you’ll learn πŸš€ βœ” Run containers as non-root users βœ” Restrict privileges inside containers βœ” Control which pods can talk to each other βœ” Apply real security patterns used in production

πŸ” 1. Pod Security Context (Lock Down the Container)

By default, containers can run with more privileges than they should. A Security Context lets you enforce restrictions like:

  • Running as a non-root user
  • Blocking privilege escalation
  • Removing unnecessary Linux capabilities

πŸ“„ File: 01-pod-security-context.yaml

apiVersion: v1
kind: Pod

metadata:
  name: security-context-demo

spec:

  # Pod-level security settings
  securityContext:

    runAsUser: 1000      # Run container as non-root user (UID 1000)
    runAsGroup: 3000     # Assign group ID
    fsGroup: 2000        # Controls file permissions on mounted volumes

  containers:

  - name: sec-ctx-demo

    image: busybox

    # Keep container alive for testing
    command: ["sh", "-c", "sleep 3600"]

    securityContext:

      allowPrivilegeEscalation: false   # Prevent gaining extra privileges

      capabilities:
        drop:
          - ALL   # Remove ALL Linux capabilities (very important)

    volumeMounts:
    - name: sec-ctx-vol
      mountPath: /data/demo

  volumes:
  - name: sec-ctx-vol
    emptyDir: {}   # Temporary storage inside pod

This configuration applies least privilege principles:

  • πŸ‘€ Runs as a non-root user β†’ safer by default
  • 🚫 Blocks privilege escalation β†’ stops exploits
  • πŸ”’ Drops all capabilities β†’ removes unnecessary power
Real-world insight πŸ’‘ Most security breaches in containers happen because apps run as root. This single change massively reduces your attack surface.

πŸš€ Run & Test

kubectl apply -f 01-pod-security-context.yaml

Verify the user inside the container:

kubectl exec security-context-demo -- id

You should see UID 1000 instead of root (UID 0).

Now test privilege restriction:

kubectl exec security-context-demo -- date -s "2024-01-01"

❌ This should fail β€” proving privilege escalation is blocked.


🌐 2. Network Policies (Control Traffic Between Pods)

By default, Kubernetes allows all pods to talk to each other. That’s dangerous in production.

Goal 🎯 Only allow frontend pods to talk to the API. Block everything else.

πŸ“„ File: 02-network-policy.yaml

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy

metadata:
  name: api-allow-frontend

spec:

  # Apply policy to API pods
  podSelector:
    matchLabels:
      app: api

  policyTypes:
  - Ingress   # Only control incoming traffic

  ingress:
  - from:

    # Only allow pods with label app=frontend
    - podSelector:
        matchLabels:
          app: frontend

    ports:
    - protocol: TCP
      port: 8080

This policy means:

  • βœ… Frontend pods β†’ can access API
  • ❌ Everything else β†’ blocked

πŸ“„ File: 03-api-deployment.yaml

apiVersion: apps/v1
kind: Deployment

metadata:
  name: api-deployment

spec:
  replicas: 1

  selector:
    matchLabels:
      app: api

  template:
    metadata:
      labels:
        app: api

    spec:
      containers:
      - name: nginx

        image: nginx:1.14.2

        ports:
        - containerPort: 8080

This creates a simple API service using nginx on port 8080.

πŸš€ Apply Everything

kubectl apply -f 03-api-deployment.yaml
kubectl expose deployment api-deployment --port=8080
kubectl apply -f 02-network-policy.yaml

πŸ§ͺ Test the Security

❌ Test from unauthorized pod:

kubectl run test-pod --image=busybox --rm -it -- wget -T 2 http://api-deployment:8080

This should fail (timeout) β€” access denied.

βœ… Test from allowed frontend pod:

kubectl run frontend --labels=app=frontend --image=busybox --rm -it -- wget -T 2 http://api-deployment:8080

This should succeed πŸŽ‰


🧠 What You Just Achieved

Feature What it does
Security Context Runs containers with minimal privileges
Network Policy Controls which pods can communicate
Least Privilege Only allow what is absolutely necessary
Senior Dev Insight πŸ’‘ If you’re not using Network Policies, your cluster is basically an open network. In production, that’s a serious risk.

🧹 Cleanup

kubectl delete pod security-context-demo
kubectl delete deployment api-deployment
kubectl delete service api-deployment
kubectl delete networkpolicy api-allow-frontend

πŸ’‘ Final Thoughts

You’ve just implemented two of the most important Kubernetes security layers:

  • πŸ” Container-level security (Security Context)
  • 🌐 Network-level security (Network Policies)

These are foundational skills for anyone working in DevOps or cloud engineering.

What’s next? πŸ‘€ In the next post, we’ll explore jobs and how they come into play in kubernetes.

Leave a Reply

Your email address will not be published. Required fields are marked *