Kubernetes NetworkPolicies: Ingress, Egress, and the AND/OR Selector Trap
Policies are additive allow-lists with no deny rules. How one indentation level turns an airtight namespace rule into a cluster-wide hole, and why DNS breaks after default-deny.

Quick Summary
A NetworkPolicy is a namespaced, label-based firewall for pods. It selects pods with podSelector and declares which traffic is allowed in (ingress) and out (egress). The rule that surprises everyone: policies are additive allow-lists. A pod selected by any policy for a direction has that direction default-denied, and only matching rules permit traffic. There are no deny rules — the way to deny is to omit.
Three conditions must hold for traffic to pass: the destination pod is selected by a policy whose ingress matches the source, the source pod is selected by a policy whose egress matches the destination (if egress is enforced), and the CNI plugin in the cluster actually implements NetworkPolicy. Flannel alone does not; Calico, Cilium, Antrea, and most managed CNIs do.
Namespaces are labels too. namespaceSelector selects whole namespaces by label, podSelector selects pods in the policy's own namespace, and combining them in one from element is an AND, while listing them as separate elements is an OR — the detail that makes a rule either airtight or wide open.
Basic Syntax & Core Signatures
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: api-allow-web
namespace: shop
spec:
podSelector:
matchLabels: { app: api }
policyTypes: [Ingress, Egress] # omitted => Ingress only (or Egress if egress rules exist)
ingress:
- from:
- namespaceSelector:
matchLabels: { kubernetes.io/metadata.name: shop }
podSelector:
matchLabels: { app: web } # AND: pods of app=web in namespace shop
ports:
- protocol: TCP
port: 8080
- protocol: TCP
port: 9000
endPort: 9010 # range, needs endPort support
egress:
- to:
- namespaceSelector:
matchLabels: { kubernetes.io/metadata.name: kube-system }
podSelector:
matchLabels: { k8s-app: kube-dns }
ports:
- { protocol: UDP, port: 53 }
- { protocol: TCP, port: 53 }
- to:
- namespaceSelector:
matchLabels: { kubernetes.io/metadata.name: data }
ports:
- { protocol: TCP, port: 5432 }# Default deny for every pod in the namespace: select all, allow nothing
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: shop
spec:
podSelector: {}
policyTypes: [Ingress, Egress]kubectl -n shop get networkpolicy
# NAME POD-SELECTOR AGE
# default-deny-all <none> 3d
# api-allow-web app=api 3d
kubectl -n shop describe networkpolicy api-allow-web
kubectl get pods -n shop --show-labels
kubectl get ns --show-labelsKey Comparison Table
| Field | Selects | Scope |
|---|---|---|
podSelector (top level) | Pods the policy applies to | Own namespace only |
ingress.from[].podSelector | Source pods | Own namespace only |
ingress.from[].namespaceSelector | Source namespaces by label | All pods in matching namespaces |
Both in one from entry | Source pods in matching namespaces | AND |
Separate from entries | Either source | OR |
ipBlock | CIDR ranges | With except for carving holes |
| Behaviour | Rule |
|---|---|
| No policy selects a pod | All traffic allowed |
One policy selects it for Ingress | Only listed ingress allowed |
| Several policies select it | Rules add up (union of allows) |
policyTypes omitted | Ingress implied; Egress implied only if egress rules exist |
Empty podSelector: {} | Every pod in the namespace |
No ports in a rule | All ports from that source |
No from in an ingress rule | All sources |
| Explicit deny | Not expressible; omit instead |
| Symptom | Meaning |
|---|---|
| Traffic blocked with no policy | Another policy selects the pod |
Egress enforced, DNS fails | No egress rule to kube-system on port 53 |
| Rule has no effect | CNI does not implement NetworkPolicy |
503 from a Service | Pods reachable by the client but not by the proxy path, or vice versa |
Practical Edge Cases & Deep Dives
1. AND versus OR in from — one indentation level decides everything
from:
- namespaceSelector: { matchLabels: { env: prod } }
podSelector: { matchLabels: { app: web } } # prod namespaces AND app=web
---
from:
- namespaceSelector: { matchLabels: { env: prod } } # any pod in prod namespaces
- podSelector: { matchLabels: { app: web } } # OR any app=web pod in this namespaceThese two blocks look nearly identical and are not. The first permits only pods labelled app=web inside namespaces labelled env=prod. The second permits everything in prod namespaces plus every app=web pod in the policy's own namespace — which in a shared cluster is usually a hole. Ingress controllers and monitoring are the usual accidental beneficiaries.
2. Default deny that does not lock you out
# Order does not matter: this is additive with the allow policies above
spec:
podSelector: {}
policyTypes: [Ingress, Egress]Apply default-deny-all to a namespace and every pod in it loses all traffic except what other policies allow — including DNS, which breaks service discovery silently (the app resolves nothing, or resolves slowly). The minimum egress for any namespace is DNS to kube-system, plus a route to whatever it calls. Note that a pod's own traffic to itself (localhost) and to the node it runs on is unaffected by NetworkPolicy in most implementations.
When rolling this out: enable policyTypes: [Ingress] first, watch, then add egress. Deploy policies alongside the workload in the same manifest so a namespace never exists in a half-configured state.
3. ipBlock, node CIDRs, and traffic that never reaches the pod network
ingress:
- from:
- ipBlock:
cidr: 10.0.0.0/8
except:
- 10.244.0.0/16 # carve out the pod CIDR
ports: [{ protocol: TCP, port: 443 }]ipBlock matches packet source addresses, and for traffic arriving from outside the cluster that can be the node IP (with externalTrafficPolicy: Cluster), a load balancer address, or the real client IP (externalTrafficPolicy: Local). kube-proxy's SNAT changes which of those you see, so an ipBlock rule that worked in staging can stop matching after a Service change. Health checks from the cloud load balancer are the classic case: they come from node IPs or a documented LB range, never from the pod network.
Traffic to the API server is not governed by NetworkPolicy; kube-apiserver and kubelet traffic is outside the CNI's enforcement path in most distributions.
4. Named ports, endPort, and protocol details
ports[].port accepts a number or a named port that matches a container port name, and endPort turns a single entry into an inclusive range. Protocol defaults to TCP; UDP and SCTP are allowed. Rule matching is on the destination port for ingress and the destination port for egress — meaning an egress rule to a service on 443 is written as 443 even if the server answers from an ephemeral source port, because policy is evaluated on the initial packet.
ports:
- { protocol: TCP, port: 8080, endPort: 8085 }
- { protocol: UDP, port: 53 }5. Policies are namespaced; ingress controllers and cross-namespace access are not
A NetworkPolicy only selects pods in its own namespace. To allow an ingress controller running in ingress-nginx to reach pods in shop, you write the policy in shop with a namespaceSelector matching the controller's namespace label. The controller's own policy is irrelevant.
kubectl get ns ingress-nginx --show-labels
# kubernetes.io/metadata.name=ingress-nginx,... (automatic since 1.21)Every namespace created since Kubernetes 1.21 carries kubernetes.io/metadata.name=<name> as an immutable label, so namespaceSelector on that label needs no manual labelling. Rely on it instead of inventing a label scheme that new namespaces will not get.
Common Runtime & Configuration Mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Policy applied, traffic still flows | CNI does not enforce NetworkPolicy | Verify the CNI (Calico/Cilium/Antrea) |
| Traffic blocked unexpectedly | A default-deny in the namespace | Read all policies selecting the pod |
| DNS breaks after egress policy | No UDP/TCP 53 egress rule | Allow kube-system DNS on 53 |
| Ingress controller gets 503 | Controller namespace not allowed | namespaceSelector on the controller namespace |
| Health checks fail | ipBlock does not match node/LB IPs | Allow the node CIDR or LB range |
| Rule "works in staging" | Different SNAT from externalTrafficPolicy | Match the actual source addresses |
| Only some pods affected | podSelector matches fewer labels than intended | kubectl get pods --show-labels |
| Cross-namespace rule ignored | Policy written in the wrong namespace | Policy belongs to the destination namespace |
| Egress to a Service name fails | Policy matches IPs after resolution | Allow the endpoint CIDR range |
| Metrics/logs stop after rollout | Monitoring namespace not allowed | Add monitoring to the allow list |
A NetworkPolicy answers one question per pod and direction: "which peers may talk to me?" Every mistake above is a mismatch between what the author pictured and what the selector actually selected. Dump the pod's labels, dump every policy in the namespace, and check the CNI last.
Try matching browser tools
All toolsSmall utilities that fit Kubernetes work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Kubernetes guides
All Kubernetes guideskubectl Output: jsonpath, custom-columns, and the Debugging Commands Worth Knowing
jsonpath for one value in a script, custom-columns for tables people read, and kubectl debug when the container has no shell. Includes the three quoting layers that break jsonpath.
Kubernetes Namespaces, ResourceQuotas, and LimitRanges
A namespace is only a boundary when quota and limit range make it one. Aggregate caps, per-pod defaults, the admission errors they produce, and namespaces stuck Terminating.
Kubernetes StatefulSets: Ordinal Identities, Headless Services, and PVC Lifecycle
Why each StatefulSet pod keeps a name, a DNS record, and its own PVC; how OrderedReady gates startup on readiness; and how partition-based updates canary a single quorum member.
Kubernetes securityContext, Capabilities, and Pod Security Standards
The five fields that remove most container escapes, which of them only exist at container level, and how the restricted profile enforces the same settings at admission.
More in Kubernetes
All Kubernetes guidesThe guides filed next to this one in Kubernetes, in library order.