Pod Selectors in Rules
What you'll learn: How to use podSelector within ingress and egress rules to control traffic based on pod labels, not just which pods the policy applies to.
Understanding Pod Selectors in Two Places
You've already learned that NetworkPolicies use podSelector at the top level to choose which pods the policy affects. But podSelector can also appear inside ingress and egress rules to specify where traffic is allowed to come from or go to.
Think of it like a guest list: the top-level podSelector says "this rule applies to the VIP room," while the podSelector inside a rule says "only guests wearing blue badges can enter."
Pod Selectors in Ingress Rules
When you place podSelector in an ingress rule, you're defining which pods are allowed to send traffic to the selected pods:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-from-frontend
spec:
podSelector:
matchLabels:
app: backend
ingress:
- from:
- podSelector:
matchLabels:
tier: frontend
This allows pods labeled tier: frontend to reach pods labeled app: backend.
Pod Selectors in Egress Rules
Similarly, in egress rules, podSelector specifies which pods your selected pods can send traffic to:
egress:
- to:
- podSelector:
matchLabels:
app: database
This allows outbound traffic only to pods labeled app: database.
Combining with Namespace Selectors
You can combine podSelector with namespaceSelector in the same rule to be even more precise about traffic sources or destinations.
Key Takeaway: Use podSelector within ingress/egress rules to filter traffic by the source or destination pod's labels, creating fine-grained network segmentation based on workload identity.