Skip to content
LF Cert Trainer

Lesson 88 · Section 7: Security

Lesson 88: Developing network policies: from requirements to a tested policy

A repeatable way to write a NetworkPolicy: turn the requirement into a traffic table, isolate the Pods, add one allow rule per row, tell AND from OR in the selectors, add egress without breaking DNS, and prove the result with tests in both directions. · 20 min read · 3 min video

1/10Developing network policies
0:00 / 3:25

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

What "developing" a policy means

The previous lesson explained what a NetworkPolicy is: a list of allowed connections for a group of Pods, enforced by the network plugin. Knowing the fields is not the hard part. The hard part is going from a sentence such as "only the API may talk to the database" to a policy that allows exactly that, breaks nothing else, and that you can prove is working.

Developing a network policy is that process. It always has the same shape: write down the traffic, isolate the Pods, open one path at a time, and test in both directions. The exam gives you the sentence and checks the result, so a fixed routine is worth more than a memorised YAML file.

This lesson uses one scenario from start to finish. In namespace prod there are three Pods, web, api and db, and the task reads:

  • api Pods in prod may connect to db on TCP 3306.
  • The reports Pod in namespace analytics may also connect to db on TCP 3306.
  • db may send backups to the server 192.168.5.10 (outside the cluster) on TCP 80.
  • No other traffic may enter or leave db.
The traffic the database needs, and nothing more3306803306blockedblockedPod apiprod, role=apiPod dbprod, role=dbBackup server192.168.5.10Pod reportsns analyticsPod webprod, role=webEverything elseother Pods, internet
The traffic the database needs, and nothing more. Draw this before you write YAML. Every solid arrow becomes one allow rule on the db Pod; everything dashed is what isolation removes for you.

Parts:

  • Pod api (prod, role=api)
  • Pod db (prod, role=db)
  • Backup server (192.168.5.10)
  • Pod reports (ns analytics)
  • Pod web (prod, role=web)
  • Everything else (other Pods, internet)

Connections:

  • Pod api to Pod db: 3306
  • Pod db to Backup server: 80
  • Pod reports to Pod db: 3306
  • Pod web to Pod db: blocked
  • Pod db and Everything else: blocked

How it works

The six steps

The six steps of developing a policy1. Traffic tablewho, direction, port2. Check labelsPods and namespaces3. Isolateselect Pods, no rules4. Allow rulesone per table row5. Read it backkubectl describe6. Test both waysallowed and blocked
The six steps of developing a policy. The YAML is step four of six. Most broken policies come from skipping the steps around it.

Parts:

  • 1. Traffic table (who, direction, port)
  • 2. Check labels (Pods and namespaces)
  • 3. Isolate (select Pods, no rules)
  • 4. Allow rules (one per table row)
  • 5. Read it back (kubectl describe)
  • 6. Test both ways (allowed and blocked)

Connections:

  • 1. Traffic table to 2. Check labels
  • 2. Check labels to 3. Isolate
  • 3. Isolate to 4. Allow rules
  • 4. Allow rules to 5. Read it back
  • 5. Read it back to 6. Test both ways
StepWhat you doWhy
1. Traffic tableOne row per connection: source, destination, direction, portEach row becomes one rule. Missing rows become outages
2. Check labelskubectl get pods,ns --show-labelsPolicies match labels only. A label that is not there matches nothing, silently
3. IsolateA policy that selects the Pods and lists policyTypes, with no rulesGives you a known starting point: everything closed
4. Allow rulesOne ingress or egress rule per table rowSmall rules are easy to read and to test
5. Read it backkubectl describe networkpolicyShows how the API server understood your indentation
6. Test both waysOne connection that must work, one that must failA policy that blocks nothing also passes the "it works" test

Step 1: the traffic table

Always describe a connection from the point of view of the Pod the policy selects, and by who opens it. For db:

RowDirection for dbOther sidePortRule
1IngressPods role=api in prodTCP 3306ingress.from with podSelector
2IngressPod app=reports in analyticsTCP 3306ingress.from with namespaceSelector and podSelector
3Egress192.168.5.10TCP 80egress.to with ipBlock

Notice what is not in the table: the answers that db sends back to api. Policies are about connections, not packets. When a connection is allowed, its reply traffic is allowed automatically, in the other direction, with no rule of its own. You only need an egress rule for connections that db itself starts.

Step 2: labels are the only thing a policy can see

A policy cannot name a Pod, a Deployment or a Service. It can only match labels, on Pods and on namespaces. So look before you write:

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

NAME        STATUS   AGE   LABELS
analytics   Active   9m    kubernetes.io/metadata.name=analytics
prod        Active   9m    kubernetes.io/metadata.name=prod

Every namespace carries the label kubernetes.io/metadata.name, set by the control plane to the namespace's own name, and it cannot be changed. That label is how you select "the namespace called analytics" when nobody has labelled the namespaces for you.

Step 3: isolate the Pods

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: db-policy
  namespace: prod              # a policy only selects Pods in its own namespace
spec:
  podSelector:
    matchLabels:
      role: db                 # the Pods this policy protects
  policyTypes:
    - Ingress
    - Egress

A Pod is open in a direction until some policy that selects it lists that direction in policyTypes. From then on the Pod is isolated for that direction, and only connections allowed by a rule get through. This policy selects db, lists both directions and has no rules, so db is now closed both ways.

Write policyTypes out every time. If you leave it out, Kubernetes assumes Ingress, and adds Egress only when the policy has an egress section. That default is a trap in both directions: a policy meant to deny all egress does nothing if it has no policyTypes, and an egress rule added later silently isolates outgoing traffic.

Step 4: one rule per row

Rows 1 and 2 share the port, so they fit in one ingress rule with two sources. Row 3 is an egress rule.

  ingress:
    - from:
        - podSelector:                 # row 1: api Pods, in this namespace
            matchLabels:
              role: api
        - namespaceSelector:           # row 2: reports Pod, in analytics only
            matchLabels:
              kubernetes.io/metadata.name: analytics
          podSelector:
            matchLabels:
              app: reports
      ports:
        - protocol: TCP
          port: 3306
  egress:
    - to:
        - ipBlock:                     # row 3: the backup server
            cidr: 192.168.5.10/32
      ports:
        - protocol: TCP
          port: 80

How to read a rule: inside one rule, from (or to) says who and ports says which port, and both must match. Several rules in the ingress list are alternatives. So "A on port 1, and B on port 2" needs two rules; put them in one rule and both A and B get both ports.

AND and OR in the selectors

One list item or two: AND or ORallowsallowsand alsoOne list itemnamespace AND Podreports in analyticsthe only matchTwo list itemsnamespace OR PodAll of analyticsevery Pod therereports in prodthe policy's namespace
One list item or two: AND or OR. Selectors inside one item of from must all match. Separate items are alternatives. A single dash is the whole difference.

Parts:

  • One list item (namespace AND Pod)
  • reports in analytics (the only match)
  • Two list items (namespace OR Pod)
  • All of analytics (every Pod there)
  • reports in prod (the policy's namespace)

Connections:

  • One list item to reports in analytics: allows
  • Two list items to All of analytics: allows
  • Two list items to reports in prod: and also

The three kinds of source or destination behave like this:

In a from or to itemMatches
podSelector alonePods with these labels in the policy's own namespace
namespaceSelector aloneEvery Pod in the namespaces with these labels
namespaceSelector and podSelector in the same itemPods with these labels, only in those namespaces (AND)
ipBlockAn address range. Cannot be combined with the selectors

Items of the list are alternatives (OR). Compare two policies that differ by one character:

# One item: reports Pods AND in analytics
- from:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: analytics
      podSelector:
        matchLabels:
          app: reports
# Two items: every Pod in analytics, OR reports Pods in prod
- from:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: analytics
    - podSelector:
        matchLabels:
          app: reports

Both are valid YAML and both are accepted. The second one opens the database to a whole namespace.

Egress and the DNS trap

Row 3 points at an IP address, so the policy above is complete. Now suppose the backup job used a name, such as backup.example.com, or db had to call another Service by name. Isolating egress also blocks the DNS lookup, and the application fails with "bad address" or a timeout before it ever tries the real connection. The fix is one more egress rule, to the cluster DNS Pods:

    - to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: kube-system
          podSelector:
            matchLabels:
              k8s-app: kube-dns
      ports:
        - protocol: UDP
          port: 53
        - protocol: TCP
          port: 53

Two details about egress to Services. First, a policy cannot name a Service. You allow the Pods behind it. Second, port is the port the connection arrives on at the destination Pod, which is the Service's targetPort, not the Service's own port. A Service that listens on 80 and forwards to 8080 needs port: 8080 in the policy.

What always gets through

  • Reply traffic of an allowed connection, as described above.
  • Traffic from the Pod's own node. The kubelet must reach the Pod for liveness and readiness probes, so connections from the node the Pod runs on cannot be blocked by a NetworkPolicy.
  • Traffic inside the Pod. Containers of one Pod talk over localhost, which policies do not cover.

And one thing that never gets blocked or allowed, because nothing is enforcing: a cluster whose network plugin does not implement NetworkPolicy. The API server stores the object, kubectl get shows it, and all traffic still flows. Calico, Cilium, Antrea and kube-router enforce policies; Flannel on its own does not. This is exactly why step 6 includes a test that must fail.

Under the hood · Several policies on one Pod, and other things worth knowing
  • Policies add up. If three policies select db, a connection is allowed when any of them allows it. There is no order, no priority and no deny rule, so a second policy can only open more, never close something.
  • A namespace-wide default deny plus small allow policies is the usual production layout: one policy with podSelector: {} and both policyTypes, then one small policy per application. Because policies add up, each team can add its own without touching the others.
  • Both ends must agree. If api is itself isolated for egress, it needs an egress rule to db on 3306 as well as db needing the ingress rule. A connection passes only when the source's egress side and the destination's ingress side both allow it.
  • ipBlock is for addresses outside the cluster. Pod IPs change with every restart, so never put them in a policy. Also, traffic that enters or leaves through a Service or a cloud load balancer may have its source address rewritten before the policy sees it, so test an ipBlock rule instead of trusting it. except carves ranges out of a block: cidr: 10.0.0.0/8 with except: [10.244.0.0/16].
  • Port ranges and names. port: 32000 with endPort: 32768 allows a range. port may also be the name of a container port, such as mysql, which survives a change of the number.
  • Existing connections. What happens to a connection that was open before the policy arrived depends on the network plugin. Do not assume it is cut; restart the client if you need certainty.

Using it

Example · Build the database policy step by step

Create the isolating policy first and confirm that the database is closed:

kubectl apply -f db-policy.yaml             # step 3: podSelector and policyTypes only
kubectl -n prod exec api -- nc -zv -w 2 db 3306
nc: db (10.103.41.7:3306): Connection timed out
command terminated with exit code 1

Good: the plugin enforces policies. Now add the ingress and egress sections from step 4 to the same file and apply it again:

kubectl apply -f db-policy.yaml
kubectl -n prod describe networkpolicy db-policy
Spec:
  PodSelector:     role=db
  Allowing ingress traffic:
    To Port: 3306/TCP
    From:
      PodSelector: role=api
    From:
      NamespaceSelector: kubernetes.io/metadata.name=analytics
      PodSelector: app=reports
  Allowing egress traffic:
    To Port: 80/TCP
    To:
      IPBlock:
        CIDR: 192.168.5.10/32
        Except:
  Policy Types: Ingress, Egress

Each From: block is one list item. A namespace selector and a Pod selector under the same From: are combined with AND, which is what the task asked for.

Example · Test the allowed and the blocked paths

Test from the real Pods when their image has a tool such as nc, wget or curl:

kubectl -n prod exec api -- nc -zv -w 2 db 3306            # must open
kubectl -n prod exec web -- nc -zv -w 2 db 3306            # must time out
kubectl -n analytics exec reports -- nc -zv -w 2 db.prod 3306   # must open

When the image has no such tool, start a throwaway Pod that carries the same labels. To the policy it is indistinguishable from the real client:

kubectl -n prod run t1 --rm -it --restart=Never --image=busybox:1.37 \
  --labels=role=api -- nc -zv -w 2 db 3306
kubectl -n prod run t2 --rm -it --restart=Never --image=busybox:1.37 \
  --labels=role=web -- nc -zv -w 2 db 3306
db (10.103.41.7:3306) open
pod "t1" deleted
nc: db (10.103.41.7:3306): Connection timed out
pod "t2" deleted
pod prod/t2 terminated (Error)

Egress is tested from the selected Pod itself, or from a test Pod with its labels:

kubectl -n prod run t3 --rm -it --restart=Never --image=busybox:1.37 \
  --labels=role=db -- nc -zv -w 2 192.168.5.10 80          # must open
kubectl -n prod run t4 --rm -it --restart=Never --image=busybox:1.37 \
  --labels=role=db -- nc -zv -w 2 1.1.1.1 443              # must time out

Example · Default deny for a namespace, then open DNS for everyone

A common task: "isolate all Pods in namespace prod, but keep name resolution working".

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
  namespace: prod
spec:
  podSelector: {}              # every Pod in prod
  policyTypes:
    - Ingress
    - Egress
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-dns
  namespace: prod
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

The two policies add up: every Pod in prod may resolve names and do nothing else, until further policies open application paths. Check the DNS labels on your cluster with kubectl -n kube-system get pods --show-labels.

Example · Allow a whole namespace, on one port

"Any Pod in namespace monitoring may scrape Pods labelled app=web in prod on port 9100."

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-monitoring
  namespace: prod              # where the protected Pods live
spec:
  podSelector:
    matchLabels:
      app: web
  policyTypes:
    - Ingress
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: monitoring
      ports:
        - protocol: TCP
          port: 9100

The policy is created in prod, not in monitoring. A policy always lives next to the Pods it selects, and describes the other side with selectors.

Tricks

Common mistakes

  • One dash too many in from. - namespaceSelector followed by - podSelector is OR, and opens a whole namespace. For "these Pods in that namespace", podSelector sits in the same item, without a dash.
  • Creating the policy in the wrong namespace. The policy goes in the namespace of the Pods it protects. Without metadata.namespace or -n, it lands in default and selects nothing useful.
  • Expecting podSelector to reach across namespaces. Alone, it only matches Pods in the policy's namespace. Pods elsewhere need a namespaceSelector in the same item.
  • Forgetting DNS when isolating egress. Connections by name fail first. Allow UDP and TCP 53 to the DNS Pods.
  • Writing an egress rule for replies. Not needed. Rules describe who opens the connection.
  • Leaving out policyTypes. An "egress deny" policy without it only isolates ingress.
  • Using the Service port. ports is the port on the destination Pod, the Service's targetPort.
  • Typing a label that does not exist. No error, no warning, no match. Copy labels from --show-labels.
  • Testing only the path that should work. On a plugin without policy support everything "works". Test a path that must fail too.

Recap

  • Developing a policy is a routine: traffic table, labels, isolate, allow rules, read back, test both ways.
  • Policies only allow. Isolate the Pods with podSelector and policyTypes, then add one rule per connection.
  • Describe traffic from the selected Pod's side and by who opens the connection. Replies are automatic.
  • Selectors in one from or to item are AND; separate items are OR. podSelector alone means "this namespace".
  • Select a namespace by name with the label kubernetes.io/metadata.name.
  • Use ipBlock for addresses outside the cluster, and remember DNS (port 53, UDP and TCP) when you isolate egress.
  • Several policies on one Pod add up, and the policy lives in the namespace of the Pods it selects.
  • Prove it: kubectl describe networkpolicy, then one connection that must open and one that must time out.

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

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

  • An egress policy was meant to let one app call one service and nothing else. It cut off everything. Find both faults and fix them without opening the door wide.

    Fix · Level 3 · challenge · target 20 min

Discussion

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