Skip to main content

Configuring Kubernetes Network Policies

Learn to write Kubernetes NetworkPolicies that default-deny pod traffic, then allow only the pod, namespace, DNS and IP paths each service needs.

52 Terms

Overview and What You Will Learn

A Kubernetes NetworkPolicy is a firewall rule for pods: it lists which traffic may reach the pods it selects and which traffic they may send, and anything not listed is dropped. Without any policy, every pod can reach every other pod in every namespace, so a compromised frontend pod can connect straight to a database. In this lab you will build a default-deny baseline in a test namespace and then add only the allow rules each workload needs. It needs a disposable cluster whose CNI enforces NetworkPolicy.

  • Applying a default-deny baseline to a namespace
  • Allowing DNS so pods can still resolve service names
  • Allowing pod-to-pod traffic on both the client and the server side
  • Allowing traffic across namespaces without opening too much
  • Testing that allowed and denied paths behave as intended
  • Debugging a policy that silently blocks traffic

Why This Matters in Production

By default a cluster is a flat network, so one compromised pod can attack everything else. Imagine a platform team at a company like Razorpay running several teams in one cluster. If an attacker gains a shell in a frontend pod, the default network lets them connect to the payments database directly and try to dump it. With default-deny plus explicit allow rules, that frontend cannot reach the database at all, and an attacker who lands in one pod can reach only what that pod was permitted to reach.

Core Principles

NetworkPolicies work as allow-lists. A pod that no policy selects accepts and sends all traffic, but once a policy selects it for a direction, only the traffic that some policy allows in that direction is permitted. There are no deny rules, so you build security by selecting pods and then listing what to allow.

flowchart TD A{Does any policy select
this pod for this direction?}:::q -->|no| ALL[All traffic allowed]:::warn A -->|yes| B{Does any rule
match the traffic?}:::q B -->|yes| OK[Traffic allowed]:::ok B -->|no| DROP[Traffic dropped]:::bad classDef q fill:#FFEDD5,color:#1E293B classDef warn fill:#F59E0B,color:#111827 classDef ok fill:#10B981,color:#FFFFFF classDef bad fill:#EF4444,color:#FFFFFF

Six rules explain nearly every NetworkPolicy surprise:

  1. A pod is isolated per direction. Listing Ingress in policyTypes isolates incoming traffic, and listing Egress isolates outgoing traffic. A policy with only Ingress leaves egress open.
  2. Both ends must allow a connection. When the client's egress and the server's ingress are both isolated, you need an egress rule on the client and an ingress rule on the server.
  3. Always allow DNS in egress. If you isolate egress without allowing port 53, pods cannot resolve any name, and every service call fails even when the connection itself is allowed.
  4. Selectors inside one from entry are ANDed, separate entries are ORed. This is the most common source of rules that allow far more than intended.
  5. Namespace selectors match labels. Kubernetes 1.21 and later label every namespace with kubernetes.io/metadata.name, so you can select a namespace by name without adding your own label.
  6. Your CNI must enforce policies. The API accepts NetworkPolicy objects even when the CNI ignores them.

The two forms below look almost identical but mean different things. The first allows only pods labeled app: nginx-ingress that live in the gateway namespace, and the second allows every pod in gateway plus every pod labeled app: nginx-ingress in the policy's own namespace:

YAML
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: gateway
podSelector:
matchLabels:
app: nginx-ingress
YAML
# OR: two list entries, which is much broader
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: gateway
- podSelector:
matchLabels:
app: nginx-ingress
Remember

Flannel does not enforce NetworkPolicy. Calico, Cilium and Antrea do, and managed clouds enforce it through an add-on or a specific dataplane, such as the VPC CNI network policy feature on EKS, Dataplane V2 or Calico on GKE, and Azure or Cilium network policy on AKS. Check your cluster before you rely on a policy.

Detailed Step-by-Step Practical Lab

Step 1 - Create Test Workloads

Create a namespace with a stand-in database (nginx, which answers HTTP on port 80), a stand-in API and a frontend. The same policy shapes apply to PostgreSQL on port 5432. Use a disposable cluster, never a shared one:

Bash
kubectl create namespace netpol-lab
kubectl run payments-db --image=nginx:1.27 --port=80 -l app=payments-db -n netpol-lab
kubectl expose pod payments-db --port=80 -n netpol-lab
kubectl run payments-api --image=nicolaka/netshoot -l app=payments-api -n netpol-lab -- sleep 3600
kubectl run frontend --image=nicolaka/netshoot -l app=frontend -n netpol-lab -- sleep 3600
kubectl wait --for=condition=Ready pod --all -n netpol-lab --timeout=120s
Step 2 - Confirm the Open Default

With no policy, both the API and the frontend can reach the database. Both should print 200:

Bash
for p in payments-api frontend; do
echo "$p -> payments-db"
kubectl exec -n netpol-lab $p -- curl -sS -m 3 -o /dev/null -w "%{http_code}\n" http://payments-db
done
Step 3 - Apply Default Deny

An empty podSelector selects every pod in the namespace, and listing both policy types with no rules denies everything in both directions:

YAML
# default-deny-all.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: netpol-lab
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
Bash
kubectl apply -f default-deny-all.yaml
kubectl exec -n netpol-lab payments-api -- curl -sS -m 3 http://payments-db
# Expected: curl: (6) Could not resolve host: payments-db

The failure is a DNS error, not a connection error, because egress to the DNS server is now blocked too.

Step 4 - Allow DNS for Every Pod

Allow egress on port 53 to the cluster DNS pods in kube-system:

YAML
# allow-dns-egress.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-dns-egress
namespace: netpol-lab
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
Bash
kubectl apply -f allow-dns-egress.yaml
kubectl exec -n netpol-lab payments-api -- curl -sS -m 3 http://payments-db
# Expected now: a timeout, because the name resolves but the connection is blocked
Tip

If your cluster runs NodeLocal DNSCache, DNS queries go to a link-local address on the node instead of the kube-dns pods. Allow that address with an ipBlock rule, or your DNS policy will not match.

Step 4b - Allow the API to Reach the Database

Because both directions are isolated, you need two policies: egress on the API and ingress on the database:

YAML
# allow-api-egress-to-db.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-api-egress-to-db
namespace: netpol-lab
spec:
podSelector:
matchLabels:
app: payments-api
policyTypes:
- Egress
egress:
- to:
- podSelector:
matchLabels:
app: payments-db
ports:
- protocol: TCP
port: 80
YAML
# allow-db-ingress-from-api.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-db-ingress-from-api
namespace: netpol-lab
spec:
podSelector:
matchLabels:
app: payments-db
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: payments-api
ports:
- protocol: TCP
port: 80
Bash
kubectl apply -f allow-api-egress-to-db.yaml -f allow-db-ingress-from-api.yaml
Step 5 - Test Allowed and Denied Paths

Test the allowed path and the denied path in the same loop. The API should print 200, and the frontend should time out:

Bash
for p in payments-api frontend; do
echo "$p -> payments-db"
kubectl exec -n netpol-lab $p -- curl -sS -m 3 -o /dev/null -w "%{http_code}\n" http://payments-db
done
Step 6 - Allow Traffic from Another Namespace

Create a gateway namespace with an nginx-ingress pod and an unrelated pod, and a web pod in the lab namespace:

Bash
kubectl create namespace gateway
kubectl run nginx-ingress --image=nicolaka/netshoot -l app=nginx-ingress -n gateway -- sleep 3600
kubectl run other --image=nicolaka/netshoot -l app=other -n gateway -- sleep 3600
kubectl run payments-web --image=nginx:1.27 --port=80 -l app=payments-web -n netpol-lab
kubectl expose pod payments-web --port=80 -n netpol-lab
kubectl wait --for=condition=Ready pod --all -n gateway --timeout=120s

Allow ingress to payments-web only from the nginx-ingress pod in the gateway namespace, using the AND form:

YAML
# allow-from-gateway.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-from-gateway
namespace: netpol-lab
spec:
podSelector:
matchLabels:
app: payments-web
policyTypes:
- Ingress
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: gateway
podSelector:
matchLabels:
app: nginx-ingress
ports:
- protocol: TCP
port: 80
Bash
kubectl apply -f allow-from-gateway.yaml
for p in nginx-ingress other; do
echo "gateway/$p -> payments-web"
kubectl exec -n gateway $p -- curl -sS -m 3 -o /dev/null -w "%{http_code}\n" \
http://payments-web.netpol-lab.svc.cluster.local
done
# Expected: nginx-ingress prints 200, other times out
Step 7 - Allow Specific External IP Ranges

For partners with fixed addresses, such as a payment gateway, use ipBlock. This is a reference snippet to adapt, not a lab step:

YAML
ingress:
- from:
- ipBlock:
cidr: 103.21.244.0/22
except:
- 103.21.244.100/32
ports:
- protocol: TCP
port: 443

ipBlock matches the packet's source IP. If a load balancer or kube-proxy rewrites the source address, the policy sees the node or load balancer IP instead of the client's, so test with real traffic.

Step 8 - Debug a Blocked Connection

A blocked connection just times out, with no message that a policy caused it. Work through these checks in order:

Bash
# 1. What policies exist, and which pods do they select?
kubectl get networkpolicy -n netpol-lab -o wide
# 2. Read the full rules of one policy
kubectl describe networkpolicy allow-db-ingress-from-api -n netpol-lab
# 3. Do the pod labels really match the selectors?
kubectl get pods -n netpol-lab --show-labels
# 4. Does the policy select any pods at all? An empty result means a label typo
kubectl get pods -n netpol-lab -l app=payments-db

On a Cilium cluster, Hubble shows the dropped packets directly:

Bash
hubble observe --namespace netpol-lab --verdict DROPPED --last 50
Step 9 - Clean Up
Bash
kubectl delete namespace netpol-lab gateway

Production Best Practices & Common Pitfalls

Common Mistake

Applying a policy whose podSelector matches no pods because of a label typo. The policy is active but protects nothing, and all traffic still flows. After every policy, run kubectl get networkpolicy -o wide and confirm the POD-SELECTOR column shows the labels you intended.

Security

Egress rules are what stop data exfiltration. A compromised pod with open egress can send data to any server, so give workloads only the outbound destinations they need and review them as carefully as ingress rules.

Tip

Cilium adds a CiliumNetworkPolicy resource with HTTP-aware rules, such as allowing only GET requests to a path prefix from one namespace. That layer 7 control goes well beyond the port and IP rules of standard NetworkPolicy.

  • Roll out default-deny namespace by namespace. Applying it to a busy namespace breaks every flow you did not list, so start with a quiet namespace and add rules from observed traffic.
  • Keep policies next to the workload. Store each service's policies in the same repository and chart as its Deployment so they change together.
  • Use the automatic namespace label. Select namespaces with kubernetes.io/metadata.name instead of hand-maintained labels that can drift.
  • Allow monitoring explicitly. Prometheus and log agents need ingress or egress rules too, or dashboards go blank after default-deny.
  • Test after every change. A short script that checks the allowed and denied paths catches mistakes before an incident does.

Quick Reference & Troubleshooting Commands

Command Description
kubectl get networkpolicy -n NS -o wide List policies and the pods they select
kubectl describe networkpolicy NAME -n NS Show a policy's full ingress and egress rules
kubectl get pods -n NS --show-labels Check that pod labels match selectors
kubectl get namespace NS --show-labels Check namespace labels used by selectors
kubectl exec POD -n NS -- curl -sS -m 3 URL Test one path from a pod
hubble observe --verdict DROPPED Show packets dropped by policy on Cilium
Symptom Likely cause Fix
All name lookups fail after default-deny Egress to DNS is blocked Add a DNS egress policy
Client times out though the server allows it Client egress is isolated and not allowed Add the matching egress rule
Policy exists but nothing changes CNI does not enforce policy, or the selector matches no pods Check the CNI and the POD-SELECTOR column
Rule allows too many pods from entries ORed instead of ANDed Put both selectors in one entry
Cross-namespace traffic blocked Namespace label missing or wrong Use kubernetes.io/metadata.name

Resources

Velero vs etcd Snapshot: Which Do You Need?

Velero vs etcd Snapshot: Which Do You Need?

Velero and etcd snapshots protect different layers of a Kubernetes cluster. See what each backs up, what each misses, and why most DR needs both.

11 min read•Aug 2026
Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient cuts the sidecar tax at L4, but L7 adds waypoint hops, and Linkerd stable builds now come from Buoyant. Choose with tests.

11 min read•Aug 2026
Nginx Ingress vs Traefik vs Gateway API in 2026

Nginx Ingress vs Traefik vs Gateway API in 2026

Ingress-NGINX is retired. Compare Traefik and Gateway API controllers as replacements, plus a safe migration plan that avoids outages.

10 min read•Aug 2026
OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno compared for 2026: Rego vs YAML, mutation, reporting, and operations, plus how to pick a Kubernetes policy engine.

10 min read•Aug 2026
Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize compared for 2026 - templating vs patching, Helm 4's new features, and why most production teams end up running both.

5 min read•Aug 2026
Prometheus vs Datadog vs New Relic: Real Costs

Prometheus vs Datadog vs New Relic: Real Costs

Prometheus, Datadog, and New Relic compared for 2026 - real pricing at scale, hidden cost drivers, and which fits a Kubernetes-heavy stack.

5 min read•Aug 2026
Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter on EKS: scale-up speed, bin-packing, Spot handling, Auto Mode limits and a safe migration path, with v1 NodePool YAML.

11 min read•Aug 2026
GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE, EKS, and AKS compared for 2026 - control plane pricing, Autopilot vs Karpenter vs Node Auto Provisioning, and which platform actually fits your team.

5 min read•Aug 2026
K3s vs K8s vs MicroK8s: Which Distro in 2026?

K3s vs K8s vs MicroK8s: Which Distro in 2026?

Compare K3s, upstream Kubernetes and MicroK8s on footprint, datastores, HA and updates, and pick the right fit for edge, dev or production.

10 min read•Aug 2026
Canary Deployments with Argo Rollouts & Flagger

Canary Deployments with Argo Rollouts & Flagger

Ship to 5% of users first and auto-rollback on bad metrics: canary deployments on Kubernetes with Argo Rollouts, Flagger, and Gateway API.

11 min read•Jun 2026
OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry in practice: instrument a Node.js service, run a production Collector, sample traces and link metrics, logs and traces in Grafana.

11 min read•Jun 2026
Kubernetes Cost Optimization Without SLO Risk

Kubernetes Cost Optimization Without SLO Risk

Kubernetes clusters average about 8% CPU use. Cut waste safely with request rightsizing, autoscaling, spot, and OpenCost, keeping SLOs.

11 min read•Jun 2026
ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD compared for 2026: UI, multi-tenancy, Helm, image automation and pruning risks, with a clear guide to picking your GitOps engine.

10 min read•Jun 2026

Explore More in Kubernetes Networking and Traffic Management

All 6 Topics

Frequently Asked Questions

Is Configuring Kubernetes Network Policies free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Configuring Kubernetes Network Policies topic cover?

Learn to write Kubernetes NetworkPolicies that default-deny pod traffic, then allow only the pod, namespace, DNS and IP paths each service needs.

Found a mistake, an outdated step or a broken link?