KCSA Isolation, Segmentation and Kubernetes Network Policy
Kubernetes isolation and segmentation is the practice of separating workloads and tenants inside one cluster with namespaces plus the controls attached to them, and a NetworkPolicy is the namespaced object that restricts which Pods, namespaces and IP ranges may connect to or from selected Pods. This lesson covers what a namespace does and does not isolate, how ResourceQuota and LimitRange contain tenants, how NetworkPolicy isolation, policyTypes, default-deny policies, selectors, ipBlock and ports behave, why egress policies must allow DNS, why the network plugin has to enforce policies, and what the NetworkPolicy API cannot do.
On this page10 sections
- What a namespace does and does not isolate
- ResourceQuota and LimitRange
- How NetworkPolicy isolation works
- policyTypes and its defaults
- Default-deny and allow-all policies
- Selecting peers: podSelector, namespaceSelector and AND versus OR
- ipBlock, ports and endPort
- Egress isolation and DNS
- Enforcement: the network plugin and Pod start-up
- What NetworkPolicy cannot do
- Explain what a namespace provides on its own and which objects add API, resource and network isolation for each tenant
- Distinguish ResourceQuota from LimitRange and predict how quota admission treats existing Pods, Pods without requests and Deployments
- Predict which traffic a set of NetworkPolicies allows, using per-direction isolation, additive rules, both-ends agreement and implicit replies
- Write default-deny and allow-all policies and work out the effective policyTypes when the field is omitted
- Read from and to peers correctly: AND versus OR, podSelector namespace scope, kubernetes.io/metadata.name and NotIn exclusions
- Choose between podSelector and ipBlock, use ports and endPort, and allow DNS under default-deny egress
- Explain why the network plugin must enforce NetworkPolicy, how policies behave at Pod start-up, and what the API cannot do
What a namespace does and does not isolate
A namespace scopes names and gives namespaced controls a place to live; on its own it neither limits resources nor blocks network traffic. Namespace-per-tenant is the common Kubernetes multi-tenancy model, but a bare namespace only means two tenants can both have a Deployment called api. Real segmentation comes from the objects you add to each namespace:
| Layer | Object | What it isolates |
|---|---|---|
| API access | Role and RoleBinding (RBAC) | Who can read or change objects in the namespace |
| Aggregate consumption | ResourceQuota | The namespace's total CPU, memory, storage and object counts, so one tenant cannot starve the others |
| Per-container values | LimitRange | Default requests and limits, plus minimum and maximum bounds for each container or Pod |
| Pod traffic | NetworkPolicy | Which Pods, namespaces and external ranges may connect to or from the namespace's Pods |
The Pod network is flat by default: any Pod can reach any other Pod in any namespace until a NetworkPolicy, enforced by the network plugin, isolates it. Data-plane isolation can go further with dedicated node pools for sensitive tenants (taints, tolerations and node affinity) and sandboxed runtimes; those node-level controls are covered in the KCSA lesson on isolation, image and code security. Pod Security Admission (which Pod settings a namespace accepts) and RBAC details have lessons of their own in this domain.
ResourceQuota and LimitRange
A ResourceQuota caps what a whole namespace can consume in total; a LimitRange sets defaults and bounds for each individual container or Pod. They are near-twins that are usually deployed together.
| ResourceQuota | LimitRange | |
|---|---|---|
| Scope | The sum across the namespace | Each container, Pod or PersistentVolumeClaim |
| Typical fields | requests.cpu, requests.memory, limits.cpu, limits.memory, object counts such as pods | default, defaultRequest, min, max |
| Stops | A runaway tenant exhausting cluster capacity | A single container asking for too much, or running with no values at all |
| Fills in missing values? | No | Yes, through its defaults |
Both are enforced at admission, when an object is created or updated. A request that would push the namespace over its quota is rejected with HTTP 403 Forbidden. Nothing already running is evicted or throttled: changing or adding a quota does not affect resources that already exist, so a namespace that is over a new quota keeps its Pods and simply cannot grow until usage falls. CPU throttling comes from container limits on the node, not from quota.
Two behaviours catch people out:
- A compute quota makes values mandatory. Once a namespace has a quota on
cpuormemory(requests or limits), every new Pod must specify that value or it is rejected. A LimitRange with defaults injects the values automatically, so developers do not have to change their manifests. - Quota rejects Pods, not their controllers. Creating a Deployment succeeds even when quota will refuse its Pods; the rejection happens when the ReplicaSet tries to create each Pod. The symptom is a Deployment that exists with no Pods, and the reason appears in the ReplicaSet's events.
Keep the scope of each object straight: these two govern how much a namespace and its containers may request, while scheduling priority, preemption and voluntary-eviction budgets are separate scheduling and availability features with no say over resource caps or defaults.
How NetworkPolicy isolation works
A NetworkPolicy is a namespaced allow list: it isolates the Pods its podSelector selects for the directions it lists, then allows only the traffic its rules describe. It works at layer 3 and 4 (IP addresses and TCP, UDP or SCTP ports) and identifies Pods by labels.
- Pods start non-isolated. A Pod that no policy selects accepts every inbound connection and may open any outbound one. A policy affects only the Pods it selects, never its neighbours.
- Ingress and egress isolation are independent. A Pod is isolated for ingress only if some policy that selects it has
Ingressin itspolicyTypes, and for egress only if one hasEgress. Isolating inbound traffic leaves outbound traffic completely open, including to external addresses. - Policies are additive. When several policies select the same Pod for a direction, the allowed traffic is the union of all of them. Policies never conflict, and creation order, names and evaluation order make no difference. A newer policy cannot take away what an older one allows.
- Both ends must agree. A connection between two Pods succeeds only if the source's egress side and the destination's ingress side both allow it. If either Pod is not isolated in that direction, its side allows everything.
- Replies are implicit. Once a connection is allowed, its reply traffic flows back without any rule in the opposite direction. A default-deny egress policy therefore does not stop a Pod answering a connection it accepted; it stops the Pod opening new ones.
- Policies apply at Pod level, equally to init containers, sidecars and regular containers. One container in a Pod cannot be exempted on its own.
Traffic between a Pod and the node it runs on is always allowed, whatever the policies say.
policyTypes and its defaults
The policyTypes field says which directions a policy isolates; when it is omitted, Kubernetes always sets Ingress and adds Egress only if the policy contains egress rules. The field is optional and a policy without it is valid, but the defaults produce surprises:
| Policy written as | Effective policyTypes | Result for the selected Pods |
|---|---|---|
No policyTypes, only ingress rules | Ingress | Inbound limited to the rules; outbound untouched |
No policyTypes, only egress rules | Ingress and Egress | Outbound limited to the rules; all inbound denied, because Ingress is set with no ingress rules |
policyTypes: [Ingress], no rules | Ingress | All inbound denied; outbound untouched |
policyTypes: [Ingress, Egress], no rules | Ingress and Egress | All new connections denied both ways |
Ingress rules never restrict outbound connections, and egress rules never restrict inbound ones: the ports and peers in a rule apply only to its own direction. Writing policyTypes explicitly avoids accidental isolation.
Default-deny and allow-all policies
A default-deny policy selects every Pod in its namespace with an empty podSelector: {} and lists a direction in policyTypes without any rules for it. Every current and future Pod in that namespace is then isolated in that direction, and only what other policies allow gets through.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-ingress
namespace: orders
spec:
podSelector: {}
policyTypes:
- Ingress
- Add
EgresstopolicyTypesto deny new outbound connections too. - Adding an empty rule,
ingress: [{}](oregress: [{}]), matches every peer and turns the policy into allow all for that direction. - A label selector such as
app: ordersinstead of{}isolates only the matching Pods, not the whole namespace.
NetworkPolicy is namespaced, and an empty selector means all Pods in the policy's own namespace, never the whole cluster. Namespaces are flat, so a policy does not follow any parent-child relationship either. The standard API has no cluster-wide default policy: each namespace that needs default deny needs its own policy, typically created by automation when the namespace is created. Some network plugins, and the SIG Network network-policy-api project (ClusterNetworkPolicy, formerly AdminNetworkPolicy), add cluster-scoped policies, but those are not part of the core NetworkPolicy API.
Selecting peers: podSelector, namespaceSelector and AND versus OR
Each item under from or to is a peer; separate items are combined with OR, while a namespaceSelector and podSelector inside one item are combined with AND. The difference is one dash in the YAML.
# OR: two peers
- from:
- namespaceSelector:
matchLabels:
env: staging
- podSelector:
matchLabels:
tier: loader
# AND: one peer
- from:
- namespaceSelector:
matchLabels:
env: staging
podSelector:
matchLabels:
tier: loader
In the OR form, each peer is judged on its own: the namespace peer admits every Pod in a matching namespace whatever its labels, and the bare Pod peer admits matching Pods from the policy's own namespace only. In the AND form, a source must satisfy both selectors at once, so only Pods with the Pod label that also run in a namespace with the namespace label get in. kubectl describe networkpolicy shows how Kubernetes interpreted a policy.
Three rules decide what a peer matches:
- A
podSelectoron its own looks only in the policy's namespace. To reach Pods elsewhere, such as a log collector in aloggingnamespace or CoreDNS inkube-system, put anamespaceSelectorin the same peer. - Namespaces are selected by label, never by a name field. The control plane sets the immutable label
kubernetes.io/metadata.nameon every namespace, with the namespace's name as its value, sokubernetes.io/metadata.name: checkoutworks even when nobody has labelled the namespace. Labels such asnameorapp.kubernetes.io/nameexist only if someone adds them. - Exclusions are written as narrower allows. There is no deny rule, priority or reject action. To admit every namespace except one, such as
trial, use amatchExpressionsentry onkubernetes.io/metadata.namewith operatorNotInand that namespace's name as the value.
A policy must live in the namespace of the Pods it protects: its podSelector only ever selects Pods in its own namespace, so protecting a workload means creating the policy where that workload runs.
ipBlock, ports and endPort
An ipBlock peer selects an IP range by CIDR, with optional except entries, and is meant for destinations or sources outside the cluster. An external payment gateway at 198.51.100.0/24 has no labels Kubernetes can see, so a Pod that calls it needs an egress rule with to: - ipBlock: {cidr: 198.51.100.0/24}. The direction matters: whoever opens the connection is governed by its egress rules, so traffic the Pod sends goes under egress/to, and traffic it accepts under ingress/from.
Do not use ipBlock for Pods or Services inside the cluster:
- Pod IPs are ephemeral. A rolling update replaces Pods with new addresses, so an IP list stops matching; a
podSelectoron the app's labels keeps matching every new replica. - Service ClusterIPs are unreliable targets. Clients connect from Pod addresses, and whether a plugin evaluates a packet before or after a Service's virtual IP is rewritten (or after NAT on ingress) is undefined and varies by plugin.
Rules can also list ports, each with a protocol (TCP by default, or UDP or SCTP) and a numeric or named port. A peer list with no ports allows all ports. To cover a range, add endPort: it must be at least port, port must be set, and both must be numeric. endPort is a stable field, but the network plugin must support it: a plugin that does not applies the rule to the single port value only, so the rest of the range stays blocked.
Egress isolation and DNS
Default-deny egress blocks DNS too, so isolated Pods need an egress rule to the cluster DNS Pods on port 53 over both UDP and TCP. Without it, a Pod cannot turn a Service name into an address, and every rule that allows the actual destination is useless.
The DNS allow has to select the DNS Pods where they really run. CoreDNS normally runs in kube-system with the label k8s-app=kube-dns, so the peer needs a namespaceSelector on kubernetes.io/metadata.name: kube-system together with that podSelector in the same item. A podSelector alone would look for DNS Pods in the policy's own namespace and find none. The DNS answers are replies and need no ingress rule.
Putting it together: when both client and server sit under default deny in both directions, a connection by Service name has to clear every isolated side it touches. Suppose a checkout Pod calls an inventory cache Service. The checkout Pods need egress to cluster DNS (to resolve the name) and egress to the inventory Pods on the cache port; the inventory Pods need ingress from the checkout Pods on that port. Each allow opens one side only, and the default deny keeps applying to every direction no allow covers, so any one missing piece leaves the connection blocked.
Enforcement: the network plugin and Pod start-up
NetworkPolicy is defined by the Kubernetes API but enforced by the cluster's network plugin (CNI); without a plugin that supports it, policies are stored and have no effect. The API server accepts and stores a NetworkPolicy whatever plugin is installed, and kubectl reports it as created, so an unsupported plugin gives a false sense of security. Calico and Cilium are examples of plugins that enforce NetworkPolicy. None of the other components does it:
- kube-proxy programs Service routing, not policy filtering.
- Admission plugins validate objects as they are stored; they do not filter packets.
- The kubelet manages Pods and calls the runtime, which calls the network plugin; the plugin is what enforces policy.
Prove enforcement by testing that a connection your policies should deny really fails.
Timing matters too. Policies take effect on existing Pods once the plugin has processed them, with no restart needed. For a policy the plugin has already handled, new Pods it selects are isolated before they start; a Pod created before the plugin finishes handling a brand-new policy may start unprotected and be isolated shortly afterwards. Allow rules, in turn, may be applied after the isolation rules (or at the same moment), and the Kubernetes API gives no signal of when they are live. A new Pod in a default-deny namespace can therefore briefly start with no connectivity, so its first outbound calls fail even though the policies are correct. The Kubernetes documentation's guidance is to make start-up tolerate this: for example, an init container that waits until the destinations the Pod needs are reachable before the app containers run, or application retry logic. The gap is inside the plugin's rollout of rules, so the fix belongs in the Pod's start-up, not in the policies.
What NetworkPolicy cannot do
The standard NetworkPolicy API filters Pod traffic by labels, namespaces, IP ranges and ports, and nothing more. The Kubernetes documentation lists what it cannot do; other tools fill the gaps.
| Not possible with NetworkPolicy | Where it comes from instead |
|---|---|
| Logging allowed or blocked connections | The network plugin or observability tools, such as Cilium's Hubble or Calico flow logs. Kubernetes itself keeps no packet-level record of policy decisions: its audit and event mechanisms describe API objects and their changes, not the traffic a plugin filters |
| Explicit deny rules or priorities | Write exclusions as narrower allows; some plugins add their own policy types |
| Targeting a Service by name | Select the Service's backing Pods with the labels in the Service's selector (not the Service object's own metadata labels, which can differ) |
| Anything TLS (encryption, mutual authentication) | A service mesh or other proxy |
| A default policy for all namespaces | Per-namespace default-deny policies created by automation, or plugin-specific cluster policies |
| Blocking loopback traffic or traffic from the Pod's own node | Not available; node traffic is always allowed |
| Layer 7 rules such as HTTP paths or methods | A service mesh or a plugin with layer 7 policy |
Behaviour for hostNetwork Pods is undefined in the API; many plugins treat their traffic as node traffic, so do not rely on NetworkPolicy to isolate them.
Tip. KCSA questions on this topic are short definitions and scenarios. Expect to predict which traffic a set of policies allows or blocks, often with a YAML snippet, and to spot why a policy does not behave as intended: the wrong direction, defaults filled in for a missing policyTypes, AND versus OR peers, a podSelector looking in the wrong namespace, a missing DNS allow, or a plugin that does not enforce the policy. Others ask which spec gives default deny or allow all, how to select a namespace or external range, what the API cannot do, and how a tenant namespace is contained with ResourceQuota and LimitRange, including what quota admission does to Pods that already run or omit their requests. Distractors are usually real Kubernetes objects or fields that belong to another direction, scope or component.
- A namespace scopes names; RBAC, ResourceQuota, LimitRange and NetworkPolicy provide the actual tenant isolation
- ResourceQuota caps a namespace's totals at admission and never evicts running Pods; LimitRange sets per-container defaults and bounds
- A CPU or memory quota makes requests or limits mandatory, and its rejections hit the ReplicaSet's Pods, not the Deployment
- Pods are non-isolated until a policy selects them for a direction; ingress and egress isolation are independent
- Policies are additive allow lists with no deny, no priority and no order; both the source's egress and the destination's ingress must allow a connection, and replies are implicit
- Omitted policyTypes means Ingress always, plus Egress only if egress rules exist
- podSelector: {} with a policyType and no rules is default deny for that namespace only; there is no cluster-wide default in the API
- Peers in one from/to item are ANDed, separate items are ORed; a podSelector alone looks only in the policy's namespace; select namespaces with kubernetes.io/metadata.name
- ipBlock is for cluster-external ranges; default-deny egress needs a DNS allow to kube-system on port 53 UDP and TCP
- Only the network plugin enforces NetworkPolicy, including endPort; the API cannot log, do TLS, target Services by name or block node traffic
Check yourself: 3 questions on this topic
Exam-style KCSA questions on Isolation, segmentation and network policy, answered right here with an explanation after each. Want more? KCSA Kubernetes Security Fundamentals practice questions.
Frequently asked questions
Does a Kubernetes namespace isolate network traffic?
No. A Kubernetes namespace only scopes object names and holds namespaced controls. Pods in any namespace can reach Pods in every other namespace until a NetworkPolicy selects them and the network plugin enforces it. A namespace also sets no resource caps; those come from a ResourceQuota and a LimitRange created inside it.
What is the difference between a ResourceQuota and a LimitRange?
A ResourceQuota caps the total resources and object counts a whole namespace may use, such as the sum of CPU requests, and rejects new objects that would exceed it. A LimitRange works per container or Pod: it fills in default requests and limits when a manifest omits them and rejects values outside its minimum and maximum. Tenants usually get both, because a quota on CPU or memory requires every new Pod to state those values and a LimitRange can supply them.
How do you create a default-deny NetworkPolicy in Kubernetes?
A default-deny NetworkPolicy uses an empty podSelector ({}) so it selects every Pod in its namespace, and lists Ingress, Egress or both in policyTypes without any rules for those directions. Every current and future Pod in that namespace is then isolated, and only traffic allowed by other policies gets through. It covers one namespace only, so each namespace needs its own copy, and a default-deny egress policy also needs a DNS allow.
Are Kubernetes NetworkPolicies evaluated in order?
No. Kubernetes NetworkPolicies are additive allow lists with no order, priority or deny action. When several policies select a Pod for the same direction, the allowed traffic is the union of everything they allow, so a newer policy can never take away what an older one allows. To exclude a source, write a narrower allow, for example a namespaceSelector with the NotIn operator.
What does it mean when namespaceSelector and podSelector are in the same from entry?
When a namespaceSelector and a podSelector sit in the same item of a NetworkPolicy from or to list, they are combined with AND: only Pods with the matching labels inside namespaces with the matching labels are selected. If each selector starts its own list item (its own dash), they are combined with OR, which allows every Pod in the matching namespaces plus the matching Pods in the policy's own namespace.
Why does DNS stop working after a default-deny egress policy?
A default-deny egress NetworkPolicy blocks every new outbound connection from the selected Pods, including DNS queries to the cluster DNS service. Pods then cannot resolve Service names. The fix is an egress rule to the CoreDNS Pods, usually selected with a namespaceSelector on kubernetes.io/metadata.name: kube-system plus a podSelector on k8s-app: kube-dns in the same peer, on port 53 over UDP and TCP. The DNS replies need no extra rule.
Why does my NetworkPolicy have no effect?
The most common reason is that the cluster's network plugin does not implement NetworkPolicy. The API server stores the policy and kubectl reports it as created, but only the network plugin (for example Calico or Cilium) enforces it; kube-proxy, the kubelet and admission plugins do not. Other causes are a podSelector that matches no Pods, a policy created in a different namespace from the Pods it should protect, or a selector that relies on a namespace label nobody added.
Can a Kubernetes NetworkPolicy log blocked connections?
No. The standard NetworkPolicy API has no logging field, and Kubernetes itself keeps no packet-level record of policy decisions; its audit and event mechanisms describe API objects such as policies, not the connections a plugin filters. Logs of allowed or blocked connections come from the network plugin or observability tools, such as Cilium's Hubble or Calico flow logs.
Source
This lesson covers the "Kubernetes Security Fundamentals" domain of the official KCSA exam guide. Vendors revise their guides — check the source for the current version.
- KCSA certification page and curriculum — The Linux Foundation
Sign up free to mark lessons complete, bookmark topics and track your exam readiness.