Network policies

Intermediate · 19 min

Firewalling Pod traffic with NetworkPolicy: isolation by selection, additive allow rules, the AND-versus-OR trap, DNS egress, and ClusterNetworkPolicy.

Before thisThe Kubernetes network model and CNILabels, selectors, annotations and namespaces

DevOps & AI Toolkit · 19 min

Network policies

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by DevOps & AI ToolkitReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • By default every Pod can reach every other Pod. A Pod becomes isolated for ingress or egress only once some NetworkPolicy selects it for that direction.
  • Policies only allow, and they add up: traffic is permitted if any policy selecting the Pod allows it. There are no deny rules and no ordering in NetworkPolicy.
  • Within one from or to entry, namespaceSelector and podSelector are ANDed. As separate list items they are ORed. One dash changes the meaning.
  • A default-deny egress policy also blocks DNS. Allow UDP and TCP 53 to the cluster DNS Pods, or names stop resolving.
  • NetworkPolicy is enforced by the CNI plugin, and a plugin that ignores it accepts the objects silently. ClusterNetworkPolicy (v1beta1) adds admin-tier Deny and Pass rules that namespaces can't override.

A flat network is a wide-open network

The network model promises that every Pod can reach every other Pod. That’s convenient and, from a security view, alarming. A compromised frontend can open connections to the payments database, the metrics stack, and every other team’s internal APIs. In a VM world you’d put subnets and security groups between tiers. Pod IPs change constantly, so IP-based firewall rules don’t fit.

NetworkPolicy is a firewall expressed in labels. You say “Pods labelled app=api accept port 8080 only from Pods labelled app=web”, and the network plugin keeps the actual packet filters in sync as Pods come and go.

Isolation happens by selection

This is the rule that confuses everyone at first. A Pod is non-isolated, accepting everything, until some NetworkPolicy selects it. Once any policy with Ingress in its policyTypes selects the Pod, the Pod is isolated for ingress, and only traffic some policy allows gets in. Egress works the same way, separately.

So a policy does two things at once: it isolates the Pods it selects, and it allows the traffic it lists. Pods it doesn’t select are untouched. And policies are purely additive. If three policies select a Pod, the allowed traffic is the union of the three. You can’t write “deny” and you can’t order rules. Think of a guest list. A venue with no list lets anyone in. Once there’s a list, you need to be on at least one of the lists to enter, and nobody can write “not this person”.

The standard first step is a namespace-wide default deny, which selects every Pod and allows nothing:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: default-deny, namespace: shop}
spec:
  podSelector: {}
  policyTypes: [Ingress, Egress]

Then you add allow policies for the traffic you actually want.

Writing allow rules

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: api-from-web, namespace: shop}
spec:
  podSelector: {matchLabels: {app: api}}
  ingress:
  - from:
    - podSelector: {matchLabels: {app: web}}
    ports: [{port: 8080}]

Peers in from (ingress) or to (egress) can be a podSelector (Pods in the policy’s own namespace), a namespaceSelector (all Pods in matching namespaces), both together, or an ipBlock with CIDRs and except ranges for traffic leaving the cluster. Every namespace carries an automatic kubernetes.io/metadata.name label, so you can select one by name. ports can be a number, a named container port, or a range with endPort.

Rules apply to connections, not packets. Allowing ingress to api lets its replies go back even if egress is denied, because implementations track connection state.

One dash, two meanings

This is the classic mistake, and kubectl describe shows it plainly. We applied two policies on the lab cluster that differ by a single -:

# api-and: one peer with both selectors
- from:
  - namespaceSelector: {matchLabels: {team: frontend}}
    podSelector: {matchLabels: {app: web}}
# api-or: two peers
- from:
  - namespaceSelector: {matchLabels: {team: frontend}}
  - podSelector: {matchLabels: {app: web}}

kubectl describe netpol renders the first as one From: block containing both selectors: Pods labelled app=web in namespaces labelled team=frontend. The second becomes two From: blocks: any Pod in a team=frontend namespace, or any app=web Pod in the policy’s own namespace. The second is far broader, and it looks almost identical in review.

Don’t forget DNS

Default-deny egress also blocks DNS lookups, and every app breaks at once with resolution errors. Allow port 53 to the cluster DNS Pods:

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}]

Note the single dash: CoreDNS Pods in kube-system, ANDed.

Who enforces it

The API server only stores NetworkPolicies. Enforcement is the CNI plugin’s job: Calico, Cilium, Antrea and the cloud CNIs (with policy turned on) program the kernel to match. Flannel alone doesn’t, and a cluster without enforcement accepts every policy and blocks nothing, with no error. Test a policy from a throwaway Pod before trusting it.

The API has other gaps. It has no deny rules, no logging, no FQDN egress (api.stripe.com), and nothing a cluster admin can set that namespaces can’t loosen. Plugins added their own CRDs for those: Calico’s GlobalNetworkPolicy, Cilium’s CiliumNetworkPolicy with DNS-aware and layer 7 rules.

Cluster-wide policy

SIG Network’s answer for admins is ClusterNetworkPolicy, from the network-policy-api project. It graduated to v1beta1 in November 2026. It’s a CRD, not core, and needs a plugin that implements it. A ClusterNetworkPolicy sits in a tier. Admin rules are evaluated before any namespace NetworkPolicy, and Baseline rules after, as defaults that namespaces may override. Its rules have actions: Accept, Deny, and Pass (hand the decision to the next tier), with a priority from 0 to 1000 to order them:

apiVersion: policy.networking.k8s.io/v1beta1
kind: ClusterNetworkPolicy
metadata: {name: protect-kube-system}
spec:
  tier: Admin
  priority: 10
  subject:
    namespaces:
      matchLabels: {kubernetes.io/metadata.name: kube-system}
  ingress:
  - name: deny-from-tenants
    action: Deny
    from:
    - namespaces:
        matchLabels: {tenant: "true"}

That’s a rule no tenant can undo with their own NetworkPolicy, which plain NetworkPolicy could never express. It replaces the earlier AdminNetworkPolicy and BaselineAdminNetworkPolicy drafts.

About the video

The embed is Viktor Farcic’s “Kubernetes Network Policies Explained” from the DevOps & AI Toolkit channel, April 2023, 19 minutes. Its chapters introduce network policies, run an application without them, apply policies in action, and close with their pros and cons, which line up with the gaps described above. It predates ClusterNetworkPolicy. Judged from chapters and description, since transcripts can’t be fetched here, and from its “English (US) original” audio track. In deeper, Kubesimplify’s deep dive builds policies with a visual editor, and Piyush’s CKA episode shows the same policy ignored by one CNI and enforced by another.

What was run: against a local v1.37.3 API server with no CNI, we applied the default-deny, DNS, AND and OR policies above and read the AND/OR difference in kubectl describe netpol. We installed the network-policy-api v0.3.1 Standard CRD, read the tier and action definitions with kubectl explain, and applied the ClusterNetworkPolicy above. Nothing enforced any policy and no traffic was tested. Semantics are from the Kubernetes NetworkPolicy docs and the policy API’s CRD descriptions, checked 2026-11-28.

Where this fits

NetworkPolicy works at layers 3 and 4, by IP and port. Identity, encryption and per-request control between services take another layer. Next: service meshes.

Check yourself

  1. 01You create one NetworkPolicy that allows ingress to app=api from app=web. What happens to traffic from app=batch to app=api, and to traffic from app=batch to app=web?

    batch to api is now dropped: api is selected by a policy for ingress, so it's isolated and only allowed sources get in. batch to web is still allowed, because no policy selects web, so it isn't isolated.

  2. 02A policy's from list has '- namespaceSelector: {team: frontend}' and on the next line '- podSelector: {app: web}'. Who can connect?

    Any Pod in a namespace labelled team=frontend, or any Pod labelled app=web in the policy's own namespace. The two dashes make them separate peers, ORed. Without the second dash, it would mean Pods labelled app=web inside team=frontend namespaces.

  3. 03After applying a default-deny policy for Ingress and Egress, every app in the namespace fails with name resolution errors. Why?

    Egress is denied, including DNS queries to CoreDNS in kube-system. Add an egress rule allowing UDP and TCP port 53 to the kube-dns Pods, selected by namespace and pod labels.

  4. 04You applied policies on a cluster using plain Flannel and nothing is blocked. Is the YAML wrong?

    Probably not. The API server stores NetworkPolicies, but enforcing them is up to the CNI plugin, and Flannel alone doesn't. Use a plugin that enforces policy (Calico, Cilium, Antrea, or a cloud CNI with policy turned on).

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark