🎯 What It Is

A NetworkPolicy is a Kubernetes resource that controls traffic flow between Pods β€” like a firewall for your cluster.

βœ… By default, all Pods can talk to each other (open network).

πŸ”’ NetworkPolicy adds restrictions β€” β€œonly allow X to talk to Y”.

πŸ’‘ Real-World Analogy

Like a building security system:


πŸ§ͺ Example: Isolate a β€œFrontend” Pod

Step 1: Deploy two apps (no policy yet)

# frontend.yaml
apiVersion: apps/v1
kind: Deployment
meta
  name: frontend
  labels:
    app: frontend
spec:
  selector:
    matchLabels:
      app: frontend
  template:
    meta
      labels:
        app: frontend
    spec:
      containers:
      - name: nginx
        image: nginx
---
apiVersion: v1
kind: Service
meta
  name: frontend
spec:
  selector:
    app: frontend
  ports:
  - port: 80

# backend.yaml
apiVersion: apps/v1
kind: Deployment
meta
  name: backend
  labels:
    app: backend
spec:
  selector:
    matchLabels:
      app: backend
  template:
    meta
      labels:
        app: backend
    spec:
      containers:
      - name: httpd
        image: httpd

Apply:

kubectl apply -f frontend.yaml -f backend.yaml

βœ… Right now: frontend can curl <http://backend> β†’ allowed


πŸ§ͺ Step 2: Apply a NetworkPolicy to Restrict Access

# deny-all-backend.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
meta
  name: deny-all-to-backend
  namespace: default
spec:
  podSelector:
    matchLabels:
      app: backend   # ← Applies to Pods with this label
  policyTypes:
  - Ingress          # ← Control incoming traffic
  ingress: []        # ← Empty = deny ALL

Apply:

kubectl apply -f deny-all-backend.yaml

Now test:

# From frontend Pod
kubectl exec deploy/frontend -- curl -m 3 <http://backend>
# ❌ Connection timed out!