Skip to main content

Network Policy

πŸ“˜ Know

Be able to explain it and pass its lab once. Phase 6 of the Learning Path.

Docs: Network Policies Β· Declare Network Policy

Overview​

By default every Pod can reach every other Pod in the cluster, across all namespaces. A NetworkPolicy turns that into an allow-list for the Pods it selects. Once any policy selects a Pod for a direction (ingress or egress), only traffic that some policy explicitly allows gets through in that direction. Policies are enforced by the CNI plugin, not by Kubernetes itself. On a CNI without NetworkPolicy support they are accepted and silently ignored. The standard pattern is default-deny per namespace, then small allow policies per flow. The classic trap is that a default egress deny also blocks DNS, so everything fails with name-resolution errors. On the request path policies act on Pod-to-Pod traffic, after the Service has picked an endpoint.

Key concepts​

How selection works​

SituationIngress to the PodEgress from the Pod
No policy selects the PodAll allowedAll allowed
A policy selects it with policyTypes: [Ingress]Only what some policy allowsAll allowed
A policy selects it with policyTypes: [Ingress, Egress]Only what's allowedOnly what's allowed, including DNS
Several policies select itThe union of their allowsThe union of their allows

Policies only add allows. There is no deny rule and no ordering. For a connection to succeed when both sides are locked down, the client needs an egress allow and the server needs an ingress allow.

Peer selectors​

from / to entryMatches
podSelectorPods with these labels in the policy's namespace
namespaceSelectorAll Pods in namespaces with these labels
namespaceSelector + podSelector in one entryPods with these labels in those namespaces (AND)
ipBlockCIDR ranges, usually for traffic leaving the cluster

The AND/OR difference is one dash:

YAMLResult
- namespaceSelector: {matchLabels: {team: a}}
podSelector: {matchLabels: {app: web}}
One entry: web Pods in team-a namespaces (AND)
- namespaceSelector: {matchLabels: {team: a}}
- podSelector: {matchLabels: {app: web}}
Two entries: any Pod in team-a namespaces, or web Pods in this namespace (OR). Usually a bug.

Every namespace carries the label kubernetes.io/metadata.name: <name>, so you can select a namespace by name without adding labels.

Ports​

ports refer to the Pod's port (the Service's targetPort), not the Service port. Policies see traffic after the Service IP has been translated to a Pod IP.

kubectl essentials​

There is no kubectl create networkpolicy. Keep the skeletons below ready, and test with labelled throwaway Pods:

kubectl get networkpolicy # short name: netpol
kubectl describe netpol allow-frontend # human-readable allow rules
kubectl get pods --show-labels
kubectl get ns --show-labels # namespace labels for namespaceSelector

# test as a Pod carrying specific labels; -T 3 makes blocked traffic fail fast
kubectl run test --rm -it --image=busybox:1.36 --restart=Never -l app=frontend -- wget -qO- -T 3 http://api
kubectl run test --rm -it --image=busybox:1.36 --restart=Never -- nslookup api

Default deny, both directions, for every Pod in the namespace:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
spec:
podSelector: {} # every Pod in the namespace
policyTypes: [Ingress, Egress] # no rules listed = nothing allowed

Allow DNS for every Pod. Needed as soon as egress is denied:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-dns
spec:
podSelector: {}
policyTypes: [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 frontend to reach the API on its container port, from this namespace and from the ingress controller's namespace:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend
spec:
podSelector:
matchLabels: {app: api} # the Pods being protected
policyTypes: [Ingress]
ingress:
- from:
- podSelector:
matchLabels: {app: frontend}
- namespaceSelector:
matchLabels: {kubernetes.io/metadata.name: ingress-system}
ports:
- {protocol: TCP, port: 8080}
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: frontend-egress-to-api
spec:
podSelector:
matchLabels: {app: frontend}
policyTypes: [Egress]
egress:
- to:
- podSelector:
matchLabels: {app: api}
ports:
- {protocol: TCP, port: 8080}

πŸ§ͺ Lab​

Lab 6-1 β˜…β˜…β˜…

Requires: Standard lab setup Β· Lab 2-4 Β· How the tiers work.

Lock a namespace down, then open exactly one path.

kind's default CNI (kindnet) enforces NetworkPolicy. On minikube, start with --cni=calico.

Goal

  1. In namespace lab6-1, create Deployment api (registry.k8s.io/e2e-test-images/agnhost:2.53, command /agnhost netexec --http-port=8080) and a Service api on port 80 β†’ 8080.
  2. Start client Pods fe (labelled app=frontend) and other (no labels). Confirm both can reach http://api/hostname.
  3. Apply default-deny. Test again. What error do you get, and why?
  4. Apply allow-dns, allow-frontend and frontend-egress-to-api. Only the frontend should get through.

Verify

kubectl -n lab6-1 exec fe -- wget -qO- -T 3 http://api/hostname # api-...
kubectl -n lab6-1 exec other -- wget -qO- -T 3 http://api/hostname # wget: download timed out
🟑 Hints
  1. Same as Lab 2-4 steps 1–2.
  2. Two long-lived client Pods, fe labelled app=frontend and other unlabelled: kubectl run -h shows -l. Test with kubectl exec.
  3. There's no NetworkPolicy generator. Save the skeletons above as files. With egress denied, what does a Pod need before it can even find api?
  4. kubectl apply -f accepts several -f flags. A connection needs an egress allow on the client and an ingress allow on the server.
🟒 Guided
  1. Create the lab namespace.

    kubectl create namespace lab6-1
  2. Run agnhost serving HTTP on 8080.

    kubectl -n lab6-1 create deployment api --image=registry.k8s.io/e2e-test-images/agnhost:2.53 \
    --port=8080 -- /agnhost netexec --http-port=8080
  3. Put a Service in front: 80 β†’ 8080.

    kubectl -n lab6-1 expose deployment api --port=80 --target-port=8080
  4. Start two client Pods: fe carries the frontend label, other carries none.

    kubectl -n lab6-1 run fe --image=busybox:1.36 --restart=Never -l app=frontend -- sleep 3600
    kubectl -n lab6-1 run other --image=busybox:1.36 --restart=Never -- sleep 3600
    kubectl -n lab6-1 wait --for=condition=Ready pod/fe pod/other
  5. Call the API from both: both work, because nothing is denied yet.

    kubectl -n lab6-1 exec fe -- wget -qO- -T 3 http://api/hostname
    kubectl -n lab6-1 exec other -- wget -qO- -T 3 http://api/hostname
  6. Deny all ingress and egress for every Pod (the default-deny skeleton above, saved as default-deny.yaml).

    kubectl -n lab6-1 apply -f default-deny.yaml
  7. Try the frontend again.

    kubectl -n lab6-1 exec fe -- wget -qO- -T 3 http://api/hostname
    wget: download timed out

    It never got past DNS: egress to kube-dns is denied too. nslookup api fails the same way ("no servers could be reached").

  8. Allow DNS, and the frontend β†’ api path in both directions (allow-frontend.yaml holds both of those policies).

    kubectl -n lab6-1 apply -f allow-dns.yaml -f allow-frontend.yaml
  9. Frontend: succeeds.

    kubectl -n lab6-1 exec fe -- wget -qO- -T 3 http://api/hostname
  10. Unlabelled Pod: times out, because only app=frontend is allowed in.

    kubectl -n lab6-1 exec other -- wget -qO- -T 3 http://api/hostname
  11. Run the βœ… Check below, then delete everything the lab created.

    kubectl delete namespace lab6-1

βœ… Check

t() { [ "$2" = "$3" ] && echo "PASS $1" || echo "FAIL $1: got '$2', want '$3'"; }
t "frontend allowed" "$(kubectl -n lab6-1 exec fe -- wget -qO- -T 3 http://api/hostname | cut -c1-4)" "api-"
t "other blocked" "$(kubectl -n lab6-1 exec other -- wget -qO- -T 3 http://api/hostname 2>&1 | grep -o 'timed out')" "timed out"

Gotchas​

  • Egress deny kills DNS. Apps log could not resolve host; nslookup says no servers could be reached; busybox wget just times out. Always ship allow-dns with an egress deny.
  • The CNI must support it. Flannel alone ignores policies. The objects apply fine and change nothing.
  • One dash changes AND to OR. Read from entries carefully. kubectl describe netpol spells out the result.
  • Ports are Pod ports. Allowing port 80 when the Service maps 80 β†’ 8080 blocks everything.
  • podSelector in a peer is namespace-local. To allow Pods from another namespace, add a namespaceSelector in the same entry.
  • The ingress controller is a client too. After a default deny, allow its namespace or external traffic stops.
  • Policies are namespaced. A default deny must be created in every namespace you want locked down.

Scenario questions​

Q1 β˜… After applying a default-deny policy, every app in the namespace fails with "could not resolve host". Why?

Model answer
  • Clarify: does the policy cover egress as well as ingress?
  • Observe: kubectl get netpol -o yaml shows policyTypes: [Ingress, Egress] with no egress rules. nslookup from a Pod fails.
  • Hypothesise: egress deny also blocks DNS queries to kube-dns in kube-system. Every hostname lookup fails before any connection is attempted.
  • Fix: add an egress policy allowing UDP and TCP 53 to k8s-app: kube-dns in kube-system.
  • Prevent: a namespace template that always ships default-deny and allow-dns together.

Q2 β˜…β˜… Allow the API to receive traffic only from the ingress controller and Pods in its own namespace.

Model answer
  • Clarify: which namespace runs the ingress controller? Which port does the API container listen on?
  • Observe: namespaces carry kubernetes.io/metadata.name, so no custom labels are needed.
  • Hypothesise: one ingress policy selecting app: api with two from entries (OR): podSelector: {} for the same namespace and a namespaceSelector for the controller's namespace.
  • Fix: apply it on the container port and test from both sides and from a third namespace.
  • Prevent: keep policies next to the app's manifests so they deploy and get reviewed together.

Q3 β˜…β˜… A policy is applied but has no effect: blocked traffic still flows. What's wrong?

Model answer
  • Clarify: which CNI does the cluster run? Is this the first policy in the cluster?
  • Observe: check the CNI's DaemonSet in kube-system. kubectl describe netpol shows which Pods it selects; compare with kubectl get pods --show-labels.
  • Hypothesise: the CNI doesn't enforce policies (plain Flannel), the podSelector matches no Pods, or the traffic is allowed by a second policy (they union).
  • Fix: move to a CNI that enforces policy (Calico, Cilium), fix the selector, or narrow the other policy.
  • Prevent: a connectivity test in CI that proves a denied path is actually denied.

Q4 β˜…β˜…β˜… Design network isolation for a cluster shared by several teams.

Model answer
  • Clarify: may teams ever call each other? Which shared services exist (ingress, monitoring, DNS)?
  • Observe: NetworkPolicies are namespaced and additive, so the baseline must exist in every namespace.
  • Hypothesise: per team namespace: default-deny both directions, allow-dns, allow same-namespace traffic, allow from the ingress controller and monitoring namespaces. Cross-team calls are explicit, reviewed policies.
  • Fix: create the baseline automatically with each namespace (a namespace controller, Kyverno generate rules, or the platform's namespace template).
  • Prevent: trade-off: namespaced policies can be edited by the team that owns the namespace. For guard rails teams can't loosen, use the CNI's cluster-wide policies (Calico GlobalNetworkPolicy, Cilium clusterwide) or AdminNetworkPolicy. β†’ See Multi-Tenant Platform.

Summary​

  • No policy means allow all. Selecting a Pod for a direction flips it to allow-list.
  • Policies union; there is no deny rule. Default-deny is just a policy with no allows.
  • Egress deny blocks DNS. Allow UDP/TCP 53 to kube-dns every time.
  • One entry ANDs, two entries OR. Watch the dash.
  • Enforcement is the CNI's job. Verify it with a real connection test, not by reading YAML.

Next in path β†’ Security