Skip to content
LF Cert Trainer

Lesson 87 · Section 7: Security

Lesson 87: Network policies: deciding which Pods may talk to each other

Why every Pod can reach every other Pod by default, what ingress and egress mean for a Pod, how a NetworkPolicy selects Pods and isolates them, how its rules allow traffic by Pod, namespace, address and port, and why the network plugin, not the API server, enforces it. · 17 min read · 3 min video

1/9Network policies
0:00 / 2:53

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why network policies exist

Kubernetes makes networking easy with one rule: every Pod gets its own IP address and can reach every other Pod, on any node and in any namespace, without NAT. You never map ports or configure routes for Pods. The network plugin (the CNI plugin) builds that flat network for you.

The price is that nothing is separated. Picture a three-tier application in namespace prod: a web Pod that serves users, an api Pod behind it, and a db Pod with MySQL on port 3306. The application only needs web to call api, and api to call db. But the network also lets web talk straight to the database, and lets a Pod in any other team's namespace do the same. If one web Pod is compromised, the database is one connection away.

Without policies, every Pod can reach every Podallowedallowedalso allowedalso allowedPod webfrontendPod apibackendPod dbMySQL :3306Pod in other nsany team
Without policies, every Pod can reach every Pod. The Kubernetes network model gives every Pod its own address and lets it reach every other Pod, in every namespace, with no address translation. Convenient, and wide open.

Parts:

  • Pod web (frontend)
  • Pod api (backend)
  • Pod db (MySQL :3306)
  • Pod in other ns (any team)

Connections:

  • Pod web to Pod api: allowed
  • Pod api to Pod db: allowed
  • Pod web to Pod db: also allowed
  • Pod in other ns to Pod db: also allowed

A NetworkPolicy is a namespaced object that changes this. It picks a group of Pods and lists the connections those Pods are allowed to accept or to open. Everything not listed is dropped.

How it works

Ingress and egress

Ingress and egress, seen from the api Pod80803306Pod webopens to api :8080Pod apiselected by policyPod dblistens on 3306Ingress for apiweb to apiEgress for apiapi to db
Ingress and egress, seen from the api Pod. Direction is always relative to the Pod a policy selects, and it is decided by who opens the connection. Replies travel back on the same connection and need no rule.

Parts:

  • Pod web (opens to api :8080)
  • Pod api (selected by policy)
  • Pod db (listens on 3306)
  • Ingress for api (web to api)
  • Egress for api (api to db)

Connections:

  • Pod web to Pod api: 8080
  • Pod api to Pod db: 3306

Every policy describes traffic from the point of view of the Pods it selects:

  • Ingress is a connection that arrives at the selected Pod. For the api Pod, the call from web is ingress.
  • Egress is a connection the selected Pod opens. For the api Pod, the call to db is egress.

The direction is decided by who opens the connection, not by which way bytes flow. Once a connection is allowed, its replies are allowed automatically in the other direction. So the db Pod needs an ingress rule from api, and does not need an egress rule to send query results back.

The parts of a policy

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: db-policy
  namespace: prod            # a policy only affects Pods in its own namespace
spec:
  podSelector:               # 1. which Pods this policy is about
    matchLabels:
      role: db
  policyTypes:               # 2. which directions it isolates
    - Ingress
  ingress:                   # 3. what may come in
    - from:
        - podSelector:
            matchLabels:
              role: api
      ports:
        - protocol: TCP
          port: 3306
PartMeaning
metadata.namespaceThe policy lives in, and only selects Pods in, this namespace
spec.podSelectorThe Pods it applies to, by label. {} selects every Pod in the namespace
spec.policyTypesIngress, Egress or both: the directions the selected Pods become isolated in
spec.ingressA list of rules. Each rule has from (who) and ports (which ports). A connection that matches any rule is allowed
spec.egressThe same for outgoing connections, with to instead of from

Read this policy aloud: "Pods labelled role=db in prod are isolated for ingress. Connections to them are allowed from Pods labelled role=api in prod, on TCP port 3306." Nothing else can reach db now. The policy says nothing about egress, so db may still open connections anywhere.

Isolation: the rule that explains everything

  • A Pod is non-isolated for a direction while no policy that selects it lists that direction in policyTypes. All traffic in that direction is allowed, as before.
  • As soon as one policy selects it for a direction, the Pod is isolated in that direction. Only connections that at least one policy allows get through.
  • Policies add up. If two policies select the same Pod, the allowed connections are the union of both. There is no order and no priority, and a policy can never take away what another one allows.
  • For a connection between two Pods to work, the source's egress side and the destination's ingress side must both allow it. A side that is not isolated allows everything.

Who may be allowed: the four kinds of peers

A from or to list holds one or more peers:

PeerMatches
podSelectorPods with these labels in the policy's own namespace
namespaceSelectorAll Pods in the namespaces with these labels
namespaceSelector + podSelector in one itemPods with these labels, only in those namespaces
ipBlockAn IP range (CIDR), with optional except ranges. Meant for addresses outside the cluster

Items of the list are alternatives: a connection matches the rule when it matches any item. The difference between "one item with two selectors" (AND) and "two items" (OR) is one dash in YAML, and the next lesson spends time on it. Every namespace carries the label kubernetes.io/metadata.name: <its name>, which is how you select a namespace by name.

Ports are matched on the destination Pod, so a Service that maps port 80 to targetPort: 8080 needs port: 8080 in the policy. protocol is TCP (the default), UDP or SCTP, and endPort turns port into a range.

Who enforces it

Who enforces a NetworkPolicycreatewatchprogramfilterignoredkubectl applyNetworkPolicyAPI serverstores it in etcdCNI plugin agenton every nodePacket filtersiptables or eBPFPod trafficallowed or droppedFlannel alonenothing enforces
Who enforces a NetworkPolicy. The API server only stores the object. An agent of the network plugin on every node watches policies and Pods, and turns them into packet filters on that node.

Parts:

  • kubectl apply (NetworkPolicy)
  • API server (stores it in etcd)
  • CNI plugin agent (on every node)
  • Packet filters (iptables or eBPF)
  • Pod traffic (allowed or dropped)
  • Flannel alone (nothing enforces)

Connections:

  • kubectl apply to API server: create
  • API server to CNI plugin agent: watch
  • CNI plugin agent to Packet filters: program
  • Packet filters to Pod traffic: filter
  • API server to Flannel alone: ignored

The API server accepts and stores any valid NetworkPolicy, and that is all it does. The network plugin enforces it: an agent on every node watches policies, Pods and namespaces, works out which Pod IPs each policy covers, and programs packet filters (iptables, nftables or eBPF) on that node. When a Pod starts or its labels change, the agents update the filters.

Calico, Cilium, Antrea and kube-router enforce policies. Flannel on its own does not. On a cluster whose plugin does not support them, policies are created without any error and change nothing. That is why every policy you write needs a test that must fail.

Under the hood · Details worth knowing
  • Traffic from the node itself to its Pods (the kubelet's probes) is always allowed. Traffic between containers of one Pod uses localhost and is never filtered.
  • Existing connections that were open before a policy arrived may or may not be cut; that depends on the plugin.
  • ipBlock and Pods. Pod IPs change with every restart, so select Pods by label, never by IP. Traffic through a load balancer or NodePort may have its source address rewritten before the policy sees it.
  • Services are invisible to policies. A policy matches the Pods behind a Service, after kube-proxy has turned the Service IP into a Pod IP. Allowing "the Service" means allowing its Pods' labels and targetPort.
  • Empty versus missing. podSelector: {} means all Pods. ingress: [], or no ingress at all with Ingress in policyTypes, allows nothing. An ingress rule without from allows every source on its ports, and ingress: [{}] allows everything.
  • Cluster-wide policies. NetworkPolicy is always namespaced. Plugins offer their own cluster-scoped kinds (Calico's GlobalNetworkPolicy, Cilium's CiliumClusterwideNetworkPolicy), and the SIG Network policy API project works on standard cluster-wide kinds. None of these is in the CKA.

Using it

Example · Protect the database

Task: "In namespace prod, only Pods with label role=api may connect to the db Pods, on TCP 3306."

Check the labels first. A policy that names a label nobody has matches nothing, without an error:

kubectl -n prod get pods --show-labels
NAME   READY   STATUS    RESTARTS   AGE   LABELS
api    1/1     Running   0          5m    role=api
db     1/1     Running   0          5m    role=db
web    1/1     Running   0          5m    role=web

Save the policy from "The parts of a policy" as db-policy.yaml and apply it:

kubectl apply -f db-policy.yaml
kubectl -n prod get networkpolicy
networkpolicy.networking.k8s.io/db-policy created
NAME        POD-SELECTOR   AGE
db-policy   role=db        3s

Now test both ways. nc -zv -w 2 tries the port and gives up after two seconds:

kubectl -n prod exec api -- nc -zv -w 2 db 3306
kubectl -n prod exec web -- nc -zv -w 2 db 3306
db (10.96.12.40:3306) open
nc: db (10.96.12.40:3306): Connection timed out
command terminated with exit code 1

The allowed path opens and the blocked one times out. Both results together prove the policy.

Example · Isolate a whole namespace

Task: "Deny all incoming traffic to every Pod in namespace prod."

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
  namespace: prod
spec:
  podSelector: {}            # every Pod in prod
  policyTypes:
    - Ingress                # isolated for ingress, and no rules allow anything

Every Pod in prod now refuses new connections, including from other Pods in prod. Combined with the db-policy above, api can still reach db, because policies add up: db-policy allows that one path. This "default deny plus small allow policies" layout is the normal way to run a namespace.

Example · Read an existing policy

Exam tasks often hand you a policy and ask what it allows, or which Pods it affects.

kubectl -n prod describe networkpolicy payroll-policy
Name:         payroll-policy
Namespace:    prod
Spec:
  PodSelector:     name=payroll
  Allowing ingress traffic:
    To Port: 8080/TCP
    From:
      PodSelector: name=internal
  Not affecting egress traffic
  Policy Types: Ingress

Answer in three steps. Which Pods? Those labelled name=payroll in prod. Which direction? Ingress only; their outgoing traffic is untouched. What is allowed? Connections from Pods labelled name=internal in prod, to port 8080. Everything else that tries to reach payroll is dropped.

Example · Allow egress from the api Pod

Task: "The api Pods may only open connections to the db Pods on 3306. Keep DNS working."

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-egress
  namespace: prod
spec:
  podSelector:
    matchLabels:
      role: api
  policyTypes:
    - Egress
  egress:
    - to:
        - podSelector:
            matchLabels:
              role: db
      ports:
        - protocol: TCP
          port: 3306
    - ports:                 # a rule with no "to": any destination, but only on port 53
        - protocol: UDP
          port: 53
        - protocol: TCP
          port: 53

The second rule keeps name lookups working; without it, api cannot even resolve the name db. The next lesson narrows that rule to the cluster DNS Pods only.

Tricks

Common mistakes

  • Creating the policy in the wrong namespace. It must be in the namespace of the Pods it protects.
  • Expecting a policy to block something. Policies only allow. To block, isolate the Pod and do not allow it.
  • Leaving out policyTypes. The default may isolate a different direction from the one you meant.
  • Writing a rule for replies. Replies on an allowed connection are automatic.
  • Using a Service's port. Policies match the port on the Pod, the Service's targetPort.
  • Forgetting DNS when isolating egress. Every lookup by name fails first.
  • Trusting kubectl get. The object exists even when the plugin does not enforce it. Test.

Recap

  • By default every Pod can reach every other Pod, in every namespace.
  • A NetworkPolicy selects Pods in its namespace with podSelector and isolates them for the directions in policyTypes.
  • Ingress is a connection to the selected Pod, egress one it opens. Replies need no rule.
  • Rules only allow. Peers are Pods, namespaces or IP blocks, limited by ports on the destination Pod.
  • Policies add up, and a connection needs both the source's egress and the destination's ingress to allow it.
  • The network plugin enforces policies, not the API server. Always test a path that must work and one that must fail.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

3 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Write a network policy that lets one app talk to a database and keeps every other Pod out, without cutting off anything else.

    Build · Level 2 · standard · target 20 min

  • Section capstone. Prepare a namespace for an audit: a short-lived login for the auditor, read-only access for her group, an identity of its own for one app, a hardened container, and network policies that close the namespace.

    Build · Level 3 · challenge · target 40 min

  • Put a default-deny policy on a namespace, then open exactly one path into it from another namespace, without cutting the namespace's own outgoing calls.

    Build · Level 3 · challenge · target 20 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.