Sub topic 6
How a Policy Isolates Pods
This chapter assumes you know pods, labels, namespaces, and how to apply YAML with kubectl. It also assumes your cluster runs a network plugin that enforces NetworkPolicy. Without one, the objects are accepted but have no effect.
Non-isolated by default
A pod with no policy selecting it is non-isolated. It accepts traffic from any source and can send traffic to any destination. Isolation is the state a pod enters when at least one NetworkPolicy selects it.
Isolation applies per direction, so a pod can be isolated for ingress, for egress, for both, or for neither.
What makes a policy select a pod
A policy selects pods through spec.podSelector. The selector matches pods in the policy's own namespace only. A policy in demo never affects pods in staging.
An empty selector (podSelector: {}) matches every pod in the namespace.
policyTypes sets the direction
The policyTypes field lists the directions the policy isolates. The following policy isolates backend pods for ingress and defines no ingress rules:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: backend-isolate-ingress
namespace: demo
spec:
podSelector:
matchLabels:
app: backend
policyTypes:
- IngressOnce applied, backend pods accept no incoming connections. Their outgoing traffic is untouched, because Egress is not listed.
Rules open holes in isolation
Isolation starts from "deny everything" in the listed direction. Rules in ingress or egress then allow specific traffic. A rule never denies anything. It can only add an allowed path.
Two details affect what you observe:
- Replies are allowed. Traffic that answers an allowed connection passes automatically. You do not write a rule for the return path.
- Both ends count. A connection from pod A to pod B must pass A's egress rules, if A is isolated for egress. It must also pass B's ingress rules, if B is isolated for ingress. If either side blocks it, the connection fails.
Common errors
- No effect at all. The network plugin does not enforce policies, or the
podSelectorlabels do not match any pod. - Wrong namespace. The policy was applied in a different namespace than the target pods.
- Unexpected egress isolation. An
egresssection was added without checkingpolicyTypes. - One-sided rules. An ingress rule was added on the destination, but the source is egress-isolated and has no matching egress rule.
Exercise
A policy in namespace demo has podSelector: {}, no policyTypes, and a single egress rule allowing TCP 443 to any destination. Which directions are the demo pods isolated for?
Show answer
Both. With policyTypes omitted, Ingress is always added, and Egress is added because the policy has an egress section. Since there are no ingress rules, all incoming traffic to the pods is denied.