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.
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:
- A pod is isolated per direction. Listing
IngressinpolicyTypesisolates incoming traffic, and listingEgressisolates outgoing traffic. A policy with onlyIngressleaves egress open. - 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.
- 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.
- Selectors inside one
fromentry are ANDed, separate entries are ORed. This is the most common source of rules that allow far more than intended. - 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. - 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:
ingress: - from: - namespaceSelector: matchLabels: kubernetes.io/metadata.name: gateway podSelector: matchLabels: app: nginx-ingress# OR: two list entries, which is much broaderingress: - from: - namespaceSelector: matchLabels: kubernetes.io/metadata.name: gateway - podSelector: matchLabels: app: nginx-ingressRememberFlannel 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:
kubectl create namespace netpol-lab kubectl run payments-db --image=nginx:1.27 --port=80 -l app=payments-db -n netpol-labkubectl expose pod payments-db --port=80 -n netpol-lab kubectl run payments-api --image=nicolaka/netshoot -l app=payments-api -n netpol-lab -- sleep 3600kubectl run frontend --image=nicolaka/netshoot -l app=frontend -n netpol-lab -- sleep 3600 kubectl wait --for=condition=Ready pod --all -n netpol-lab --timeout=120sStep 2 - Confirm the Open Default
With no policy, both the API and the frontend can reach the database. Both should print 200:
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-dbdoneStep 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:
# default-deny-all.yamlapiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata: name: default-deny-all namespace: netpol-labspec: podSelector: {} policyTypes: - Ingress - Egresskubectl 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-dbThe 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:
# allow-dns-egress.yamlapiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata: name: allow-dns-egress namespace: netpol-labspec: 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: 53kubectl 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 blockedTipIf your cluster runs NodeLocal DNSCache, DNS queries go to a link-local address on the node instead of the
kube-dnspods. Allow that address with anipBlockrule, 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:
# allow-api-egress-to-db.yamlapiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata: name: allow-api-egress-to-db namespace: netpol-labspec: podSelector: matchLabels: app: payments-api policyTypes: - Egress egress: - to: - podSelector: matchLabels: app: payments-db ports: - protocol: TCP port: 80# allow-db-ingress-from-api.yamlapiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata: name: allow-db-ingress-from-api namespace: netpol-labspec: podSelector: matchLabels: app: payments-db policyTypes: - Ingress ingress: - from: - podSelector: matchLabels: app: payments-api ports: - protocol: TCP port: 80kubectl apply -f allow-api-egress-to-db.yaml -f allow-db-ingress-from-api.yamlStep 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:
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-dbdoneStep 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:
kubectl create namespace gatewaykubectl run nginx-ingress --image=nicolaka/netshoot -l app=nginx-ingress -n gateway -- sleep 3600kubectl 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-labkubectl expose pod payments-web --port=80 -n netpol-labkubectl wait --for=condition=Ready pod --all -n gateway --timeout=120sAllow ingress to payments-web only from the nginx-ingress pod in the gateway namespace, using the AND form:
# allow-from-gateway.yamlapiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata: name: allow-from-gateway namespace: netpol-labspec: 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: 80kubectl 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.localdone# Expected: nginx-ingress prints 200, other times outStep 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:
ingress: - from: - ipBlock: cidr: 103.21.244.0/22 except: - 103.21.244.100/32 ports: - protocol: TCP port: 443ipBlock 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:
# 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 policykubectl 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 typokubectl get pods -n netpol-lab -l app=payments-dbOn a Cilium cluster, Hubble shows the dropped packets directly:
hubble observe --namespace netpol-lab --verdict DROPPED --last 50Step 9 - Clean Up
kubectl delete namespace netpol-lab gatewayProduction Best Practices & Common Pitfalls
Common MistakeApplying a policy whose
podSelectormatches no pods because of a label typo. The policy is active but protects nothing, and all traffic still flows. After every policy, runkubectl get networkpolicy -o wideand confirm thePOD-SELECTORcolumn shows the labels you intended.
SecurityEgress 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.
TipCilium adds a CiliumNetworkPolicy resource with HTTP-aware rules, such as allowing only
GETrequests 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.nameinstead 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 |