NetworkPolicies
Write default-deny and allow rules and test them between Pods.
By Invicly Tech, , in Kubernetes Administrator (CKA). About 10 minutes to read.
In short
NetworkPolicies are Pod-level firewalls enforced by the CNI plugin. Once a policy selects a Pod for a direction, only traffic explicitly allowed by some policy is permitted. A common pattern is default deny for the namespace, then narrow allow rules by Pod and namespace labels.
Explained simply
By default, the Kubernetes network is wide open: every Pod can talk to every other Pod in every namespace. That is easy, but risky. If an attacker breaks into one Pod, they can reach your database directly.
A NetworkPolicy is a firewall rule for Pods. It picks some Pods by label and says who may talk to them (ingress) or whom they may talk to (egress). There are only allow rules. Anything not allowed is blocked, but only for Pods that some policy has selected.
The usual approach is: first block everything in a namespace with a default-deny policy, then add small allow rules, like "frontend may call api on port 8080". Think of it as locking all doors, then handing out specific keys.
Policies are enforced by the network plugin, not by Kubernetes itself. Calico and Cilium enforce them. Flannel does not, and it will silently accept your policies while blocking nothing.
Press Play on a diagram to walk through it one step at a time.
- podSelector
- Pods the policy applies to
- Empty selects all Pods
- policyTypes
- Ingress
- Egress
- ingress.from
- podSelector
- namespaceSelector
- ipBlock
- egress.to
- Same peer types
- Allow DNS on port 53
- ports
- protocol and port
- - namespaceSelector: team=a
- podSelector: app=web
- Only web Pods in team=a namespaces
- Usually what you want
- - namespaceSelector: team=a
- - podSelector: app=web
- Every Pod in team=a namespaces
- Plus web Pods in this namespace
In depth
How isolation really works
A Pod is isolated for ingress as soon as any policy with Ingress in policyTypes selects it, and the same for egress. Isolated Pods accept only traffic that at least one selecting policy allows. Policies never conflict: the allowed set is the union of all of them, so you cannot write a rule that blocks something another policy allows.
For a connection between two Pods, both ends must agree: the sender's egress rules (if it is egress-isolated) and the receiver's ingress rules (if it is ingress-isolated). Reply packets of an allowed connection are always let through, so you never need rules for responses. If you leave out policyTypes, it is set to Ingress, plus Egress only if the policy has egress rules.
- 1Is A egress-isolated?
If no, A's side allows it
- 2If yes, any egress rule?
Some policy on A must allow B and port
- 3Is B ingress-isolated?
If no, B's side allows it
- 4If yes, any ingress rule?
Some policy on B must allow A and port
- 5Both sides allow
Connection and replies flow
Selector logic: the indentation trap
Inside from or to, each list item (each dash) is a separate peer, and peers are ORed. Inside one item, a podSelector and a namespaceSelector together are ANDed: Pods with that label in namespaces with that label. One missing dash changes the meaning completely.
A podSelector alone means Pods in the policy's own namespace. A namespaceSelector alone means all Pods in matching namespaces. Every namespace has the automatic label kubernetes.io/metadata.name, so you can select a namespace by its name. An ingress rule with no from field allows any source on its ports, and ingress: [{}] allows everything. ipBlock picks CIDR ranges with optional except lists; it is meant for traffic from outside the cluster, because Pod IPs change.
- - namespaceSelector: ... + podSelector: ... (one item) means AND
- Two dashes means OR: either peer is allowed
- ports with endPort allows a range, like 32000 to 32768
Egress, DNS and Service ports
Default-deny egress also blocks DNS, so names stop resolving and every request looks like a timeout. Always pair it with a rule allowing UDP and TCP port 53 to the CoreDNS Pods: namespaceSelector kubernetes.io/metadata.name: kube-system together with podSelector k8s-app: kube-dns.
Another trap: policies see traffic after kube-proxy has rewritten the Service IP to a Pod IP. So ports in a policy must be the Pod's targetPort, not the Service port. A Service on port 80 forwarding to 8080 needs a policy allowing 8080. For the same reason, allowing a Service's ClusterIP in an ipBlock does nothing useful; select the backend Pods by label instead.
Testing policies like the grader does
Never trust a policy until you test it from both an allowed and a blocked Pod. Start temporary Pods with the labels you want to impersonate using kubectl run -l, and in the right namespace with -n. Use a short timeout (wget -T 2 or nc -w 2) so blocked attempts fail quickly instead of hanging.
A blocked connection usually times out, because packets are dropped silently. Connection refused means the network allowed it but nothing listens on that port. kubectl describe networkpolicy prints the rules in plain words, which is the fastest way to catch an AND versus OR mistake.
- kubectl run t -n prod -l app=frontend --rm -it --image=busybox:1.36 --restart=Never -- wget -qO- -T 2 api:8080
- kubectl get netpol -A lists every policy
- Test DNS separately with nslookup
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Write a default-deny policy~45m
- 2Allow traffic by pod and namespace labels~45m
- 3Control egress traffic~45m
- 4Test policies between Pods~45m
Key points
- Policies are additive allow lists; there are no deny rules.
- podSelector and namespaceSelector in one from item are ANDed; separate items are ORed.
- Default-deny egress also blocks DNS unless you allow UDP and TCP 53.
- Select namespaces by the kubernetes.io/metadata.name label.
- Policies need a CNI that enforces them, such as Calico or Cilium.
Key terms
Tap a card to flip it. 0/5 known
Examples
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: api-allow-frontend, namespace: prod }
spec:
podSelector: { matchLabels: { app: api } }
policyTypes: [Ingress]
ingress:
- from:
- podSelector: { matchLabels: { app: frontend } }
ports: [{ protocol: TCP, port: 8080 }]
# Default deny: podSelector: {} with policyTypes: [Ingress]Only frontend Pods may reach api Pods on port 8080.
Lock down a namespace but keep DNS
Requirement: in namespace prod, block all traffic in and out, except DNS lookups. Step 1: one policy with podSelector {} and both policyTypes and no allow rules for ingress. Step 2: in the same policy, allow egress to CoreDNS on port 53. Step 3: test that nslookup works and wget to an outside address fails.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: default-deny-keep-dns, namespace: prod }
spec:
podSelector: {}
policyTypes: [Ingress, Egress]
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 }]Allow the monitoring namespace to scrape metrics
Pods app=api in prod expose metrics on 9090. Only Pods labeled app=prometheus in namespace monitoring may scrape them. Step 1: write one from item with both selectors (AND). Step 2: apply. Step 3: test from a Pod with the right label in monitoring (works) and from a Pod with the same label in default (times out).
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: allow-prometheus, namespace: prod }
spec:
podSelector: { matchLabels: { app: api } }
policyTypes: [Ingress]
ingress:
- from:
- namespaceSelector: { matchLabels: { kubernetes.io/metadata.name: monitoring } }
podSelector: { matchLabels: { app: prometheus } }
ports: [{ protocol: TCP, port: 9090 }]Quick reference
- Default deny ingress: podSelector: {} and policyTypes: [Ingress] with no ingress rules
- Allow all ingress: ingress: [{}]
- One from item with both selectors = AND; separate dashes = OR
- Select a namespace by name: kubernetes.io/metadata.name: NAME
- Default-deny egress needs UDP and TCP 53 to kube-dns allowed
- Policy ports are Pod targetPorts, not Service ports
- Timeout = blocked by policy; connection refused = allowed but nothing listening
Common mistakes
- Splitting podSelector and namespaceSelector into two items, which allows far more.
- Applying default-deny egress and breaking DNS lookups.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Create a default-deny ingress policy in namespace test and show that a Pod there can no longer be reached from another Pod.
- Exercise 2medium
In test, allow only Pods labeled role=client in the same namespace to reach web on port 80. Prove it with a labeled and an unlabeled Pod.
- Exercise 3hard
Pods app=api in prod may only make outgoing connections to app=db Pods in namespace data on TCP 5432, plus DNS. Write the policy.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Can a NetworkPolicy deny specific traffic?
- No. Standard NetworkPolicies only allow. You deny by isolating Pods and not allowing that traffic. Some CNIs add their own policy types with explicit deny rules.
- Do NetworkPolicies work on every cluster?
- Only if the CNI plugin enforces them. Calico and Cilium do; Flannel on its own does not.
- Does a NetworkPolicy affect traffic between containers in the same Pod?
- No. Containers in one Pod share a network namespace and talk over localhost, which policies do not touch.