Updated on November 4, 2026
A Kubernetes network policy is a namespaced NetworkPolicy object that controls which pods can send traffic to, and receive traffic from, other pods, namespaces, and IP ranges. It uses label selectors and allow-list rules, and the cluster’s CNI plugin enforces them. Without any policy, every pod can reach every other pod. A policy isolates the pods it selects and allows only the flows you declare. This guide, current as of November 2026, explains how a Kubernetes network policy is evaluated and which CNI plugins enforce it. It then walks through a hands-on lab with ingress, egress, DNS, and namespace isolation rules.
Key takeaways
- ✓Kubernetes allows all pod-to-pod traffic until a NetworkPolicy selects a pod, and from then on that pod accepts only traffic that some policy explicitly allows.
- ✓NetworkPolicy has no deny rule, so traffic is denied when no applicable policy allows it, and multiple policies on one pod add their allowed traffic together.
- ✓Policies take effect only when the CNI plugin enforces them, so a cluster running plain Flannel or kindnet silently ignores your YAML.
- ✓Any default-deny egress policy must also allow UDP and TCP port 53 to CoreDNS, or service name resolution breaks for every selected pod.
- ✓Standard NetworkPolicy matches external destinations by IP range, not domain name, so FQDN-based egress control needs CNI-specific extensions.
How Kubernetes network policy works
A Kubernetes network policy selects pods by label and attaches allow rules for incoming traffic (ingress), outgoing traffic (egress), or both. The policy describes intent. The CNI plugin turns that intent into packet filtering on each node with iptables, nftables, or eBPF programs. NetworkPolicy is the in-cluster layer of cloud network security. Security groups and VPC firewalls cannot tell one pod from another on the same node, but NetworkPolicy can.
The semantics that trip people up
- Isolation on selection: a pod that no policy selects accepts and sends any traffic. Once a policy with
IngressinpolicyTypesselects it, the pod rejects all inbound traffic that no policy allows. Egress works the same way. - Allow-list only: there is no
denyfield. Traffic is denied when nothing allows it. - Additive: if three policies select the same pod, its allowed traffic is the union of all three. Order does not matter, and no policy can subtract what another allows.
- Both ends count: a connection from pod A to pod B needs A’s egress rules and B’s ingress rules to permit it when both pods are isolated in that direction.
- Pods, not Services: rules apply to pod IPs after Service load balancing, so they match pod labels and the container port (
targetPort). A Service mapping port 80 to targetPort 8080 needsport: 8080in the policy. - Connection tracking: reply packets for an allowed connection pass automatically, so you never write return rules.
Writing Kubernetes network policy YAML
Every Kubernetes network policy YAML manifest uses the same small set of fields.
| Field | What it does | Common mistake |
|---|---|---|
podSelector (spec) |
Chooses which pods in the policy’s namespace the policy applies to | {} selects every pod in the namespace |
policyTypes |
Declares Ingress, Egress, or both. If omitted, Kubernetes assumes Ingress and adds Egress only when an egress section exists |
Omitting it and assuming egress is isolated |
ingress.from / egress.to |
Lists allowed peers; list items are ORed | An empty rule - {} allows everything |
podSelector (peer) |
Matches pods by label in the same namespace unless combined with a namespaceSelector | Expecting it to match pods in other namespaces |
namespaceSelector |
Matches all pods in namespaces whose labels match | Selecting by namespace name instead of label |
ipBlock |
Matches a CIDR, with optional except ranges |
Using it for pod IPs, which change on every reschedule |
ports |
Restricts the rule to a protocol and port; endPort defines a range |
Using the Service port instead of the container port |
CNI plugins that enforce network policies
Network policies work only when the cluster’s CNI plugin enforces them. The API server accepts NetworkPolicy objects regardless, so an unsupported plugin ignores them without any error. The official Kubernetes guide to declaring network policy names Antrea, Calico, Cilium, and Kube-router as supporting providers, and recommends Kubernetes v1.8 or later.
| CNI plugin | NetworkPolicy support | Extensions beyond the spec | Observability | Operational complexity |
|---|---|---|---|---|
| Calico | Full | Calico NetworkPolicy and GlobalNetworkPolicy CRDs, explicit deny actions, rule ordering; domain names in Calico Enterprise | Flow logs (richer in commercial editions) | Moderate |
| Cilium | Full, eBPF-based | CiliumNetworkPolicy with L7 (HTTP, gRPC, Kafka) rules and toFQDNs egress |
Hubble flow visibility | Moderate to high |
| Antrea | Full, Open vSwitch-based | Antrea-native policies with tiers and priorities | Traceflow and flow exporter | Moderate |
| Kube-router | Full, iptables and ipset | Minimal; also provides BGP routing and a service proxy | Basic | Low |
| Flannel | None on its own | Pair it with Calico (the “Canal” setup) for enforcement | Basic | Low |
| Weave Net | Supported | None notable; no longer actively maintained | Basic | Low, with maintenance risk |
Managed platforms add their own modes. GKE Dataplane V2 is built on Cilium, and Amazon EKS can enforce policies through the VPC CNI’s network policy agent or through Calico. Check which mode your cluster actually runs before you rely on a policy.
Write standard networking.k8s.io/v1 policies first. CRDs such as CiliumNetworkPolicy or Calico GlobalNetworkPolicy add FQDN and L7 rules, but they tie your manifests to one CNI. When you need them, keep them in a clearly separated directory.
Kubernetes network policy tutorial: build and test policies step by step
The fastest way to learn network policy is to run a local kind cluster with Calico, deploy a three-tier app, and test connectivity before and after each policy. kind’s default CNI, kindnet, does not enforce policies, so the config disables it.
Create the cluster and install Calico
The config creates one control-plane node and two workers, because the Kubernetes docs recommend at least two non-control-plane nodes for testing cross-node traffic. It also sets a pod subnet that matches Calico’s default.
# kind.yaml
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
networking:
disableDefaultCNI: true
podSubnet: 192.168.0.0/16
nodes:
- role: control-plane
- role: worker
- role: workerNodes stay NotReady until a CNI is running, so wait for calico-node before you continue.
kind create cluster --name netpol-lab --config kind.yaml
kubectl apply -f https://raw.githubusercontent.com/projectcalico/calico/v3.28.0/manifests/calico.yaml
kubectl -n kube-system rollout status daemonset/calico-node
kubectl get nodesDeploy frontend, backend, and db
kubectl create deployment labels each pod app=<name>, and the policies below select pods by those labels.
kubectl create namespace shop
kubectl -n shop create deployment frontend --image=nginx:1.27
kubectl -n shop create deployment backend --image=nginx:1.27
kubectl -n shop create deployment db --image=postgres:16
kubectl -n shop set env deployment/db POSTGRES_PASSWORD=example
kubectl -n shop expose deployment frontend --port=80
kubectl -n shop expose deployment backend --port=80
kubectl -n shop expose deployment db --port=5432Test baseline connectivity
A throwaway busybox pod that carries a tier’s label stands in for that tier. Here it acts as the frontend and reaches the database directly. The test succeeds because nothing is isolated yet.
kubectl -n shop run test --rm -it --image=busybox:1.36 --labels=app=frontend \
-- nc -zv -w 2 db 5432
# db (10.96.x.x:5432) openApply a default deny and targeted allows
The empty podSelector selects every pod in shop, and the missing ingress section allows nothing in.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-ingress
namespace: shop
spec:
podSelector: {}
policyTypes:
- IngressNext, allow only backend pods to reach the database on port 5432. This is the classic Kubernetes network policy example, a database that accepts connections from exactly one tier.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: db-allow-backend
namespace: shop
spec:
podSelector:
matchLabels:
app: db
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: backend
ports:
- protocol: TCP
port: 5432A matching backend-allow-frontend policy selects app: backend and allows app: frontend on TCP 80. Apply all three files with kubectl apply -f, then rerun the test with different --labels values.
| Source to destination | Before policies | After policies |
|---|---|---|
| frontend to backend:80 | Allowed | Allowed |
| backend to db:5432 | Allowed | Allowed |
| frontend to db:5432 | Allowed | Times out |
| unlabeled pod to backend:80 | Allowed | Times out |
| backend to internet | Allowed | Allowed (egress not isolated yet) |
Denied connections time out rather than being refused, because most CNIs drop the packets. Test the denied path as carefully as the allowed one. A policy that passes only the allowed test may be allowing everything.
Troubleshooting a policy that seems ignored
- Confirm enforcement:
kubectl get pods -n kube-systemshould showcalico-node,cilium,antrea-agent, orkube-routerpods. With kindnet or plain Flannel, policies do nothing. - Check pod and namespace labels: compare
kubectl get pods -n shop --show-labelsandkubectl get ns --show-labelswith your selectors. A typo such asapp: databsematches nothing and fails silently. - Read the parsed policy:
kubectl describe networkpolicy db-allow-backend -n shopshows the selectors and ports as the API sees them. - Test from inside pods: use
kubectl execor a labeled debug pod, not your laptop, because NodePort and LoadBalancer paths may be source-NATed. - Use CNI tooling: Cilium’s Hubble or Calico flow logs show which policy dropped a flow.
Kubernetes network policy examples
Beyond basic pod-to-pod ingress, the most useful network policy examples isolate namespaces, combine namespace and pod selectors, and allow external CIDRs with ipBlock.
Using network policies for namespace isolation
Namespace isolation lets pods talk freely inside their own namespace and blocks other namespaces. Since Kubernetes v1.21, every namespace carries the immutable label kubernetes.io/metadata.name, so you can select namespaces by name without adding labels yourself.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-same-namespace
namespace: shop
spec:
podSelector: {}
policyTypes:
- Ingress
ingress:
- from:
- podSelector: {}A peer podSelector: {} with no namespaceSelector means “any pod in this namespace.” Combined with a default deny, it gives you Kubernetes network policy namespace isolation per tenant or team, a basic form of microsegmentation for Kubernetes workloads.
Allowing a monitoring namespace: AND versus OR
Indentation decides whether selectors combine. Below, one list item holds both selectors, so a pod must be labeled app: prometheus and run in the monitoring namespace.
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: monitoring
podSelector:
matchLabels:
app: prometheus
ports:
- protocol: TCP
port: 9090Add a dash before podSelector and you get two list items, which means OR. The rule then allows any pod in monitoring, plus any app: prometheus pod in the local namespace. That one character causes many over-permissive policies, so check it in review.
Allowing external CIDRs with ipBlock
Use ipBlock for traffic from outside the cluster, such as an office VPN range. This rule allows 203.0.113.0/24 except one subnet.
ingress:
- from:
- ipBlock:
cidr: 203.0.113.0/24
except:
- 203.0.113.128/25
ports:
- protocol: TCP
port: 443ipBlock caveat: cloud load balancers and ingress controllers often source-NAT traffic, so the pod sees a node or proxy IP instead of the client IP. Setting externalTrafficPolicy: Local on the Service preserves client IPs in many setups, but behavior varies by implementation, so test it on your CNI.
Controlling egress traffic with Kubernetes network policies
Kubernetes network policies control egress with egress rules that allow outbound traffic from selected pods. There is no separate Egress resource. The usual pattern is a default-deny egress policy plus explicit allows for DNS, internal dependencies, and known external IP ranges.
Default deny egress
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-egress
namespace: shop
spec:
podSelector: {}
policyTypes:
- EgressEvery pod in shop now loses outbound access, including DNS. nc -zv db 5432 fails with a name resolution error instead of a timeout, which tells you DNS is blocked.
Kubernetes network policy egress DNS rule
Allow UDP and TCP port 53 to the CoreDNS pods in kube-system. You need TCP because responses larger than 512 bytes, and some resolvers, fall back to TCP.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-dns-egress
namespace: shop
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: 53With NodeLocal DNSCache, pods query a link-local address on the node (commonly 169.254.20.10), so add an ipBlock for that address too.
Kubernetes network policy egress example for the backend
The backend needs the database and one external payment API. The db pod is isolated for ingress, so db-allow-backend must stay in place. Both ends have to allow the flow.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: backend-egress
namespace: shop
spec:
podSelector:
matchLabels:
app: backend
policyTypes:
- Egress
egress:
- to:
- podSelector:
matchLabels:
app: db
ports:
- protocol: TCP
port: 5432
- to:
- ipBlock:
cidr: 198.51.100.0/24
ports:
- protocol: TCP
port: 443Why domain names are a gap
Standard NetworkPolicy matches external destinations by IP, which breaks down for SaaS APIs whose IPs rotate. According to Tigera’s Calico documentation on Kubernetes egress, the options are IP-based rules for external networks or Calico Enterprise’s domain name support in policy rules. Cilium offers toFQDNs in CiliumNetworkPolicy. Either way, FQDN egress control depends on a CNI-specific extension, and that YAML will not carry over to another CNI.
Validating network policies against runtime traffic with Upwind
Upwind helps teams check network policies against what workloads actually do at runtime instead of trusting YAML alone. Its lightweight eBPF sensors see what is running in Kubernetes and prioritise risk by real runtime exposure. Its Agentic Pack AI agents investigate threats, validate exposure, and generate fixes. Upwind holds a 4.8/5 rating from 88 reviews on Gartner Peer Insights as of November 2026. Teams running a single small cluster with a few pod-to-pod rules may find a full CNAPP more platform than they need.
- ✓One eBPF sensor gives runtime visibility into Kubernetes workloads
- ✓It prioritises risk by real exposure rather than configuration alone
- ✓Cloud detection and response steps in when traffic or behavior turns malicious
- ✓One platform covers posture, workloads, identities, and APIs
Kubernetes network policy best practices
Kubernetes network policy best practices come down to starting from default deny, scoping every allow tightly with stable labels, and proving enforcement on every change. Network policy is one part of how to secure Kubernetes, alongside the broader Kubernetes security best practices for workloads, identities, and runtime.
- ✓Default deny per namespace: ship default-deny ingress and egress policies plus the DNS allow with every new namespace, ideally from a namespace template or admission policy.
- ✓Least privilege: allow specific pods and ports. Avoid
namespaceSelector: {}, rules withoutports, and empty podSelectors outside baseline policies. - ✓Stable labels: select on
app,tier, andteam, never on labels CI changes per release, such as image versions. - ✓Segment by namespace: map namespaces to teams or trust zones and label them (for example
env=prod) so cross-namespace rules stay readable. - ✓Test in CI: spin up a kind cluster with Calico or Cilium in the pipeline, apply the manifests, and run allowed and denied connectivity checks before merging.
- ✓Document intent: annotations stating why a flow exists and who owns it let you remove stale rules safely.
- ✓Lock down editing: role-based access control in Kubernetes should restrict
create,update, anddeleteonnetworkpoliciesto platform owners, or any namespace admin can open their own exceptions. - ✓Watch real traffic: compare observed flows with declared policy, because new dependencies show up as broken requests or overly broad allows.
A well-designed Kubernetes network policy setup is short, label-driven, and tested. Start with default deny for ingress and egress and a DNS allow, then allow each real dependency by pod label and container port. Confirm your CNI enforces the rules and treat FQDN and L7 controls as CNI extensions. Once that is in place, network segmentation becomes a dependable part of Kubernetes cluster security.
FAQ
What does a Kubernetes NetworkPolicy actually control?
A Kubernetes NetworkPolicy controls which pods can send traffic to, and receive traffic from, other pods, namespaces, and IP ranges. It uses label selectors and allow-list rules, and the cluster’s CNI plugin enforces those rules.
What happens if no NetworkPolicy is applied?
Without any policy, every pod can reach every other pod. Once a policy selects a pod for ingress or egress, that pod becomes isolated in that direction and only traffic explicitly allowed by some policy can pass.
Does Kubernetes NetworkPolicy support explicit deny rules?
No. Standard Kubernetes NetworkPolicy is allow-list only. There is no deny field, so traffic is denied when no applicable policy allows it. If multiple policies select the same pod, their allowed traffic is combined.
Why do pods lose DNS after a default-deny egress policy?
A default-deny egress policy blocks outbound traffic, including DNS. To restore name resolution, you must allow UDP and TCP port 53 to CoreDNS in kube-system. If you use NodeLocal DNSCache, you also need to allow its link-local IP address.
Can standard NetworkPolicy allow egress by domain name instead of IP?
No. Standard NetworkPolicy matches external destinations by IP range, not domain name. FQDN-based egress control requires CNI-specific extensions such as Cilium’s toFQDNs or Calico Enterprise domain-based policy rules.
