10 Kubernetes Network Policies Every Engineer Must Know

10 Kubernetes NetworkPolicy examples with YAML: default deny, DNS egress, cross-namespace, CIDR egress, port ranges, plus rollout tips and CNI support.

Dec 29, 2025 - 18:10
Nov 8, 2026 - 15:04
 0  95
10 Kubernetes Network Policies Every Engineer Must Know

The ten Kubernetes NetworkPolicies most clusters need are default deny for ingress and egress, a DNS egress allowance, same-namespace allow, frontend-to-backend by label, cross-namespace access, ingress controller access, monitoring scrapes, external egress by CIDR, port ranges, and a database lock-down. They only work if your CNI plugin enforces NetworkPolicy.

Out of the box, every pod in a Kubernetes cluster can reach every other pod. That suits a lab and causes trouble in production, because one compromised container can talk to your database, your metrics stack and the cloud metadata endpoint. NetworkPolicy is the built-in API for narrowing that down. This guide gives you ten policies with YAML you can adapt, explains the selector rules that trip people up, and shows how to roll them out without cutting off live traffic. If you need a refresher on the parts of the cluster involved, start with our Kubernetes architecture components guide.

Key takeaways

  • A NetworkPolicy has no effect unless the network plugin implements it. Calico, Cilium and Antrea do; plain Flannel does not.
  • A pod becomes isolated for a direction (ingress or egress) only when some policy selects it and lists that direction in policyTypes.
  • Policies are additive. There is no deny rule in the standard API; you deny by selecting pods and allowing nothing else.
  • A connection needs both the source pod's egress and the destination pod's ingress to allow it.
  • Put namespaceSelector and podSelector in the same list item for AND, separate items for OR. This is the most common mistake.
  • Once you deny egress, allow DNS on port 53 (UDP and TCP) or almost everything breaks.

How NetworkPolicy evaluation works

A NetworkPolicy is a namespaced object in the networking.k8s.io/v1 API group. Its podSelector picks the pods it applies to; an empty selector ({}) picks every pod in the namespace. The policyTypes field says whether the policy covers Ingress, Egress or both. If you leave it out, Kubernetes assumes Ingress and adds Egress only when the policy contains egress rules.

Three rules from the official documentation shape every design decision:

  • A pod that no policy selects for a direction is non-isolated in that direction and accepts all traffic.
  • When several policies select the same pod, the allowed traffic is the union of all of them. Order does not matter.
  • Reply traffic for an allowed connection is allowed automatically, so you do not write return rules.

Peers inside from and to can be a podSelector, a namespaceSelector, both together, or an ipBlock with a CIDR and optional except list. Since Kubernetes v1.21 every namespace carries the label kubernetes.io/metadata.name with its own name, so you can target a namespace by name without adding labels yourself.

#PolicyDirectionWhat it stops
1Default deny ingressIngressAny unsolicited inbound traffic
2Default deny egressEgressOutbound calls and data leaving pods
3Allow DNSEgressNothing; restores name resolution after #2
4Allow same namespaceIngressTraffic from other namespaces
5Frontend to backendIngressAny pod other than the frontend reaching the API
6Cross-namespace by name and labelIngressOther teams' pods
7Ingress controller onlyIngressDirect access that bypasses the ingress layer
8Monitoring scrapeIngressMetrics endpoint exposure to the whole cluster
9External egress by CIDREgressCalls to arbitrary internet hosts and metadata IPs
10Database lock-down with portsIngressEverything except the app on the database port

1. Default deny all ingress

This is the baseline for every application namespace. It selects all pods and allows no inbound traffic, so every later policy becomes an explicit exception.

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

Apply it per namespace. The standard API has no cluster-wide policy, so tools such as Calico's GlobalNetworkPolicy or Cilium's CiliumClusterwideNetworkPolicy exist for that need. Many teams template this file into every new namespace through Helm, Kustomize or a policy engine.

2. Default deny all egress

Egress control limits what an attacker can do from inside a pod: no calls to a command server, no reaching other namespaces, no hitting the cloud instance metadata service.

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

Teams often skip egress because it breaks things. Roll it out after the ingress baseline, and pair it with policy 3 on the same day.

3. Allow DNS egress to CoreDNS

With egress denied, pods cannot resolve service names. Allow UDP and TCP port 53 to the cluster DNS pods. TCP matters because large responses fall back to it.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-dns
  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: 53

Check the label on your DNS pods first with kubectl get pods -n kube-system --show-labels. Many distributions use k8s-app: kube-dns for CoreDNS, but managed services can differ. Note that the namespace and pod selectors sit in one list item, so both must match.

4. Allow traffic within the same namespace

For a small application where every component trusts the others, this is a quick way to keep east-west traffic inside the namespace while blocking everything from outside it.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-same-namespace
  namespace: shop
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector: {}

A bare podSelector in a from clause only matches pods in the policy's own namespace. Treat this as a stepping stone: it is better than an open cluster and weaker than the label-based rules below.

5. Frontend to backend by label

This is the core microservices pattern. Only pods labelled app: frontend may reach the backend API, and only on its service port.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: backend-allow-frontend
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app: backend
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
    ports:
    - protocol: TCP
      port: 8080

The port is the container port the pod listens on, not the Service port. If your Service maps 80 to 8080, write 8080 here. Labels now act as a security boundary, so restrict who can change them through RBAC and admission policy.

6. Cross-namespace access with AND logic

Shared services such as an internal payments API often need calls from another team's namespace. Here only the checkout pods in the orders namespace may connect.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: payments-allow-checkout
  namespace: payments
spec:
  podSelector:
    matchLabels:
      app: payments-api
  policyTypes:
  - Ingress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: orders
      podSelector:
        matchLabels:
          app: checkout

Now the trap. Add a dash before podSelector and you have two list items, which means OR: every pod in orders, plus any pod labelled app: checkout in the payments namespace. The YAML looks almost identical and the access is far wider. Read every cross-namespace rule twice.

7. Allow only the ingress controller

Web workloads should accept outside traffic only through the ingress or gateway layer, where TLS, rate limits and authentication live. This policy admits the controller's namespace and nothing else.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: web-allow-ingress-controller
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app: frontend
  policyTypes:
  - Ingress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: ingress-nginx
    ports:
    - protocol: TCP
      port: 8080

Change the namespace name to match your controller. If you use a cloud load balancer that sends traffic straight to pods, the source addresses are the load balancer's, and you may need an ipBlock instead. Our Kubernetes Ingress best practices post covers the controller side.

8. Allow monitoring scrapes

Prometheus needs to reach metrics ports, but those endpoints should not be open to every pod. Limit the rule to the monitoring namespace and the metrics port.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-prometheus-scrape
  namespace: shop
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: monitoring
      podSelector:
        matchLabels:
          app.kubernetes.io/name: prometheus
    ports:
    - protocol: TCP
      port: 9090

Use the port your applications expose metrics on. Remember the Prometheus pods also need egress to these targets if their namespace has a default deny egress policy.

9. External egress by CIDR, with exceptions

Some pods must call an outside API or a managed database. Allow the provider's published range and exclude the instance metadata address that clouds expose at 169.254.169.254.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-partner-api
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app: backend
  policyTypes:
  - Egress
  egress:
  - to:
    - ipBlock:
        cidr: 203.0.113.0/24
    ports:
    - protocol: TCP
      port: 443

The example uses a documentation range from RFC 5737; replace it with the real one. Standard NetworkPolicy cannot match by DNS name, and cloud API addresses change often. If you need rules such as "allow api.example.com", look at Cilium's toFQDNs or Calico's domain-based policies, or route outbound traffic through an egress gateway or proxy. Also note that ipBlock is meant for cluster-external addresses; pod IPs change, so use selectors for in-cluster peers.

10. Database lock-down with port ranges

The database should accept connections only from the application tier on its own port. Where a service needs a range of ports, the endPort field (stable since Kubernetes v1.25) covers it in one entry.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: postgres-allow-backend
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app: postgres
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: backend
    ports:
    - protocol: TCP
      port: 5432
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: media-allow-range
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app: media-relay
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
    ports:
    - protocol: UDP
      port: 32000
      endPort: 32100

Your CNI must support endPort; check its documentation before you depend on it. Port 5432 is the IANA-registered PostgreSQL port.

Rolling out policies without an outage

  1. Map real traffic first. Tools such as Cilium Hubble or Calico flow logs show which pods talk to which. Without that map, default deny becomes guesswork.
  2. Write the allow policies before the deny. Allow rules on a non-isolated pod change nothing, so you can apply them safely.
  3. Apply default deny ingress in one non-critical namespace, watch errors and latency, then move on.
  4. Add default deny egress with the DNS rule in the same commit.
  5. Test with a throwaway pod: kubectl run tmp --rm -it --image=busybox -n shop -- wget -qO- -T 3 http://backend:8080. A timeout means the policy blocks it.
  6. Store policies in Git next to the application manifests and review changes like code. A GitOps tool keeps the cluster in sync.

Existing connections may or may not be cut when a new policy lands; the documentation leaves this to the plugin. Plan rollouts as if long-lived connections could drop.

Choosing a CNI that enforces policy

PluginStandard NetworkPolicyExtra policy features
CalicoYesGlobal policies, ordered rules with explicit deny, domain-based egress in some editions
CiliumYeseBPF dataplane, L7 (HTTP, gRPC) rules, FQDN egress, Hubble visibility
AntreaYesTiered ClusterNetworkPolicy with priorities
Flannel aloneNoPair it with Calico (the "Canal" setup) for enforcement

Managed services vary. On EKS, the VPC CNI can enforce NetworkPolicy once you enable it; GKE offers Dataplane V2 based on Cilium; AKS supports Azure Network Policy Manager, Calico and Cilium. Confirm the current option in your provider's documentation before you rely on it.

Kubernetes SIG Network is also working on AdminNetworkPolicy and BaselineAdminNetworkPolicy, cluster-scoped APIs for platform teams. They are still alpha in the policy.networking.k8s.io group, so check support before planning around them.

Common mistakes

  • Applying policies on a cluster whose CNI ignores them, then assuming you are protected.
  • The AND/OR selector mix-up described in policy 6.
  • Denying egress and forgetting DNS, or allowing only UDP 53.
  • Writing the Service port instead of the container port.
  • Forgetting that the source pod's egress must also allow the connection when both namespaces are locked down.
  • Using ipBlock for pod IPs, which change on every reschedule.
  • Treating NetworkPolicy as the whole security story. Pair it with RBAC, Pod Security Admission and secrets handling, covered in our Kubernetes security best practices.

Where this fits in multi-tenant clusters

In a cluster shared by several teams, namespace isolation through policies 1, 2 and 4 is the minimum. Combine it with resource quotas and per-team RBAC, as described in our multi-tenant security practices. When something stops working after a policy change, follow the steps in debugging networking in Kubernetes, and if you need HTTP-aware rules or mutual TLS between services, compare options in our service mesh tools comparison.

NetworkPolicy is part of the Certified Kubernetes Security Specialist (CKS) curriculum and appears in CKA tasks too. Our CKS training covers it in hands-on labs, in the Kharadi, Pune classroom or live online.

Frequently asked questions

Do Kubernetes NetworkPolicies work on every cluster?

No. The API server accepts the objects on any cluster, but only a network plugin that implements NetworkPolicy, such as Calico, Cilium or Antrea, enforces them. Without one, the policies have no effect.

What is a default deny NetworkPolicy?

It is a policy with an empty podSelector and a policyTypes list but no allow rules. It isolates every pod in the namespace for that direction, so only traffic allowed by other policies gets through.

Can I write an explicit deny rule?

Not with the standard API. Policies only allow, and their effects add up. Explicit deny rules and rule ordering are available through CNI-specific resources such as Calico and Antrea policies.

Why does DNS break after I add a default deny egress policy?

Pods can no longer reach CoreDNS. Add an egress rule allowing UDP and TCP port 53 to the DNS pods in kube-system.

How do I allow traffic from a specific namespace?

Use a namespaceSelector on the automatic kubernetes.io/metadata.name label. Add a podSelector in the same list item if only certain pods in that namespace should connect.

Can NetworkPolicy filter by domain name or HTTP path?

No. Standard NetworkPolicy works at layers 3 and 4 with IPs, ports and labels. Cilium and some Calico editions add FQDN and HTTP-aware rules, and a service mesh can enforce L7 policy.

Are NetworkPolicies on the CKS exam?

Yes. Cluster setup and network segmentation, including NetworkPolicies, are part of the CNCF CKS curriculum. Check the current curriculum on the Linux Foundation Training site before you book.

References

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.