Scenario:
Create the Correct Least-Permissive NetworkPolicy
In the project-x
namespace, you have two Deployments:
-
frontend
(label:app=frontend
) -
backend
(label:app=backend
)
📋 Goal:
Allow only frontend pods in the same namespace to access the backend on TCP port 8080.
No other traffic (ingress/egress) should be allowed.
🔵 Option 1 — ❌ Overly Restrictive
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: too-restrictive
namespace: project-x
spec:
podSelector:
matchLabels:
app: backend
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 8080
🧠 Why it's overly restrictive:
✅ Matches pod labels
❌ Does not allow traffic unless frontend and backend are in the same namespace — no namespace check present (default behavior is same-namespace only).
⚠️ If frontend pods are ever moved to another namespace, this will silently fail.
🔵 Option 2 — ✅ Perfect & Least Permissive (Correct)
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend-to-backend
namespace: project-x
spec:
podSelector:
matchLabels:
app: backend
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: project-x
ports:
- protocol: TCP
port: 8080
🧠 Why it's correct:
✅ Explicitly restricts to both correct podSelector AND namespaceSelector
✅ Allows only traffic from frontend ➜ backend on port 8080
✅ Secure and scoped — no wildcards or assumptions
🔵 Option 3 — ❌ Over-Strict (IPBlock)
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: overly-strict-ipblock
namespace: project-x
spec:
podSelector:
matchLabels:
app: backend
policyTypes:
- Ingress
ingress:
- from:
- ipBlock:
cidr: 10.244.0.0/16
ports:
- protocol: TCP
port: 8080
🧠 Why it's over-strict:
❌ Uses a broad IP range instead of selecting frontend pods directly
❌ Not label-based — hard to audit or update
⚠️ If pod IPs change or move to different subnets, this could break unexpectedly
✅ Allows traffic technically, but not least-permissive
✅ Final Answer: Option 2
Comments
Post a Comment