🎯 What It Is

A “default deny” NetworkPolicy blocks all traffic (ingress and/or egress) in a namespace by default — then you explicitly allow only what’s needed.

✅ This is the gold standard for security in multi-tenant or production clusters.

💡 Real-World Analogy

Like a secure data center:


🧪 Example: Isolate the prod Namespace

Step 1: Create a “default deny all” policy for prod

# default-deny-prod.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
meta
  name: default-deny-all
  namespace: prod
spec:
  podSelector: {}           # ← Applies to ALL Pods in namespace
  policyTypes:
  - Ingress
  - Egress
  ingress: []               # ← Deny all incoming
  egress: []                # ← Deny all outgoing

Apply it:

kubectl create namespace prod
kubectl apply -f default-deny-prod.yaml

Result:


🧪 Step 2: Allow Essential Traffic (e.g., DNS + Internal Services)

Now, add allow rules for what’s needed:

# allow-dns-and-backend.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
meta
  name: allow-dns-and-backend
  namespace: prod
spec:
  podSelector:
    matchLabels:
      app: frontend
  policyTypes:
  - Egress
  egress:
  # Allow DNS (required for service name resolution)
  - ports:
    - port: 53
      protocol: UDP
    - port: 53
      protocol: TCP

  # Allow frontend → backend
  - to:
    - podSelector:
        matchLabels:
          app: backend
    ports:
    - port: 80

Apply:

kubectl apply -f allow-dns-and-backend.yaml