🎯 What It Is

An egress rule in a NetworkPolicy lets you restrict which external destinations a Pod can talk to β€” for example, β€œbackend can only call the database, not the internet.”

βœ… This is critical for security compliance and preventing data exfiltration.

πŸ’‘ Real-World Analogy

Like a corporate firewall:


πŸ§ͺ Example: Allow Backend to Talk Only to Database

Assume you have:

Step 1: Apply a NetworkPolicy to Restrict Egress from Backend

# restrict-backend-egress.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
meta
  name: backend-egress-policy
  namespace: default
spec:
  podSelector:
    matchLabels:
      app: backend          # ← Policy applies to backend Pods
  policyTypes:
  - Egress                  # ← Control outgoing traffic
  egress:
  - to:
    - podSelector:
        matchLabels:
          app: database     # ← Only allow traffic to database Pods
    ports:
    - protocol: TCP
      port: 5432            # ← PostgreSQL port

Apply it:

kubectl apply -f restrict-backend-egress.yaml

Step 2: Test Outgoing Traffic

βœ… From backend β†’ database (should work):

kubectl exec deploy/backend -- nc -zv database 5432
# βœ… Succeeded

❌ From backend β†’ internet (should fail):

kubectl exec deploy/backend -- wget -qO- <http://example.com> --timeout=3
# ❌ Connection timed out