Pod Selection with Labels
You'll learn: How to use label selectors in NetworkPolicies to precisely control which pods the security rules apply to.
The Core Idea
Just like you learned with Services and ReplicaSets, NetworkPolicies use label selectors to target specific pods. When you define a NetworkPolicy, you specify which pods it should protect by matching their labels. This is the foundation of network segmentation in Kubernetes—without proper pod selection, your security rules would either apply to everything or nothing.
Think of it like setting up security zones in an office building. You don't secure "the entire floor"—you secure "rooms labeled 'finance'" or "rooms labeled 'engineering'." Labels give you that granular control.
How It Works
In a NetworkPolicy's spec, you use the podSelector field with matchLabels or matchExpressions to identify target pods:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: db-security
namespace: production
spec:
podSelector:
matchLabels:
app: database
tier: backend
policyTypes:
- Ingress
This NetworkPolicy applies only to pods with both app: database and tier: backend labels in the production namespace. Pods without these exact labels are unaffected.
You can also use an empty podSelector: {} to apply the policy to all pods in the namespace—useful for namespace-wide default-deny rules.
Why This Matters
Precise pod selection lets you implement least-privilege networking. You can isolate sensitive workloads (databases, payment processors) while leaving development pods unrestricted. The same label-matching techniques you mastered with Services and ReplicaSets now become your network security targeting system.
Key Takeaway: Use podSelector with label matchers in NetworkPolicies to target exactly which pods should be governed by network rules—your labels become security boundaries.