Kubernetes NetworkPolicy is one of the most useful controls for reducing unnecessary traffic between workloads. A default Kubernetes namespace normally allows pods to communicate freely unless a policy selects them for isolation. That convenience helps applications work immediately, but it also means a compromised pod may be able to reach services that were never intended to be exposed to it. Network policies let platform teams describe which pods may receive connections and which destinations a pod may contact.
The resource is declarative and relatively small, but a safe rollout requires more than writing YAML. Your cluster networking plugin must enforce policies, labels must accurately represent workload identity, DNS must remain reachable when egress is restricted, and tests must verify the behavior from inside the cluster. This guide builds a practical default-deny baseline and then adds narrow application rules.
What a Kubernetes NetworkPolicy actually controls
A NetworkPolicy selects pods using labels and defines allowed ingress traffic, egress traffic or both. Ingress is traffic entering a selected pod. Egress is traffic leaving it. The standard API operates mainly at the transport layer for TCP, UDP and, where supported, SCTP. It is not a replacement for application authentication, service-mesh identity or a web application firewall.
By default, if no NetworkPolicy selects a pod for a direction, Kubernetes permits traffic in that direction, subject to other cluster controls. Once one or more policies select a pod for ingress or egress, that direction becomes isolated and only traffic allowed by the union of matching rules is permitted. Multiple policies are additive: a later policy can add an allowed path, but it does not subtract a path already allowed by another policy.
This additive behavior is important during design. A policy called deny-all does not override a broad allow policy that selects the same pods. Review every policy that matches the target labels, not only the newest YAML file.
Confirm that your CNI plugin enforces NetworkPolicy
Kubernetes stores NetworkPolicy objects in the API, but the network plugin implements enforcement. Creating a policy in a cluster whose CNI does not support NetworkPolicy may have no effect. Before relying on the control, check the documentation for the installed CNI and its configuration. Also confirm whether the cluster uses a managed networking layer or an additional policy engine that changes how rules are interpreted.
# Inspect the cluster version and installed networking components
kubectl version
kubectl get pods -n kube-system -o wide
kubectl get daemonsets -n kube-system
# See existing NetworkPolicy objects
kubectl get networkpolicy -A
kubectl get networkpolicy -n production -o yaml
Do not treat an empty result from kubectl get networkpolicy as proof that no other network control exists. Cloud firewalls, node security groups, service meshes and CNI-specific policies may also affect traffic. Document the layer that owns each rule so operators know where to troubleshoot a denied connection.
Plan policy around application flows
Start with a simple traffic map. For a three-tier application, the intended paths might be: an ingress controller can reach the frontend on TCP 8080; the frontend can reach the API on TCP 8080; the API can reach PostgreSQL on TCP 5432; and application pods can reach the cluster DNS service. Everything else should be denied unless a documented requirement says otherwise.
Use stable labels such as app, component and environment. Avoid selecting workloads by generated pod names because names change during rescheduling and rollout. Namespace labels should express a controlled boundary such as environment=production or team=payments. Restrict who can edit those labels; a user who can relabel a namespace may change which policies match it.
Step 1: Apply a default-deny baseline
The following policy selects every pod in the namespace where it is created and isolates both ingress and egress. It does not contain any allow rules, so traffic is denied until another matching policy permits it. Apply it first in a non-production namespace or a canary workload, not blindly across a live namespace.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: production
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
An empty podSelector means all pods in the policy’s namespace. The policy does not automatically cover other namespaces. Create a corresponding baseline in each namespace that requires isolation, and make namespace onboarding include the policy as part of the platform template.
Step 2: Preserve DNS resolution
A default-deny egress policy also blocks DNS unless an allow rule is added. This is a common reason that applications appear to lose connectivity after a policy rollout. Inspect the actual labels on the cluster DNS pods before applying the example below. The selector k8s-app: kube-dns is common, but distributions can use different labels or a NodeLocal DNSCache arrangement.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-dns-egress
namespace: production
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
In one peer entry, the namespace selector and pod selector are combined: the destination must be a matching pod in a matching namespace. If you put them in separate list entries, the entries are alternatives rather than a combined condition. Check the labels with kubectl get pods -n kube-system --show-labels and adapt the policy to the actual DNS deployment.
Step 3: Allow frontend traffic to the API
Assume frontend pods carry app=frontend and API pods carry app=api in the same namespace. The following rule allows only frontend pods to reach API pods on TCP port 8080. The API pods remain isolated from other ingress sources.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend-to-api
namespace: production
spec:
podSelector:
matchLabels:
app: api
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 8080
If the frontend is in a separate namespace, combine a namespaceSelector and a podSelector in the same peer item. Label the namespace deliberately, for example kubectl label namespace web team=web, then use that label in the policy. Do not copy a namespace selector that matches every namespace unless that broad access is intended.
Step 4: Allow the API to reach PostgreSQL
Suppose the database runs in a namespace labelled tier=data and its pods carry app=postgres. The API egress policy can allow only TCP 5432 to that destination. The example uses a namespace label so the database namespace can be renamed without changing the policy, provided the label remains governed.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-api-to-postgres
namespace: production
spec:
podSelector:
matchLabels:
app: api
policyTypes:
- Egress
egress:
- to:
- namespaceSelector:
matchLabels:
tier: data
podSelector:
matchLabels:
app: postgres
ports:
- protocol: TCP
port: 5432
This is a pod-to-pod rule, not a substitute for database authentication or TLS. PostgreSQL should still use dedicated application roles, least-privilege grants, encrypted connections where required and private network exposure. A network policy narrows the set of workloads that can attempt a connection; it does not prove that the caller is authorized to read a particular table.
Apply policies and test both allowed and denied paths
Keep policy manifests in version control and review them like application code. Apply the policy to a test namespace, then inspect the stored object and run connectivity tests from representative pods.
kubectl apply --dry-run=server -f network-policy.yaml
kubectl apply -f network-policy.yaml
kubectl describe networkpolicy -n production
kubectl get networkpolicy -n production -o yaml
# Inspect pod labels before testing selectors
kubectl get pods -n production --show-labels
# Run a temporary test pod with the expected source label
kubectl run net-test --rm -it -n production \
--image=busybox:1.36 --labels=app=frontend -- sh
From the test pod, try to reach the API service on the expected port and then try an unrelated destination that should be blocked. Use a second test pod without the frontend label to verify that the policy rejects it. A timeout is not always proof of policy enforcement: the target may be unhealthy, DNS may be broken or a route may be missing. Compare tests before and after policy application and inspect CNI logs when the result is ambiguous.
For production rollouts, introduce policies in stages: label workloads, create the required allow rules, test the expected paths, then enable default-deny isolation. Because policy behavior is additive, check that no older broad policy still grants access. Monitor application errors and service-level indicators during each stage, and keep a documented rollback procedure.
Important limitations and common mistakes
- Assuming every CNI enforces policies: verify the actual plugin and test a known allowed and denied path.
- Forgetting DNS: default-deny egress blocks DNS unless the cluster’s DNS path is explicitly allowed.
- Misreading selector logic: selectors in one peer item are combined; separate peer items are alternatives.
- Expecting deny rules: standard NetworkPolicy is allow-list oriented and matching policies combine additively.
- Using pod IPs as identities: pod addresses are ephemeral; prefer labels and namespace selectors.
- Assuming IP blocks always see the same address: service routing and NAT can change the source or destination observed by the policy engine.
- Expecting layer-7 filtering: standard NetworkPolicy does not understand HTTP paths, users or application roles.
- Applying default deny without a traffic map: monitoring, metrics, service discovery and backup paths can break unexpectedly.
When a connection fails, verify DNS first, then inspect pod labels, namespace labels, policy selection and CNI enforcement. Check whether the destination is reached through a Service, load balancer or external address because address translation can affect IP-based rules. If the requirement is based on domain names or HTTP identity, use a suitable CNI-specific policy feature, service mesh or application-layer control rather than forcing standard NetworkPolicy to do a job it was not designed for.
Build NetworkPolicy into platform operations
Make network policy part of the namespace template and application onboarding checklist. Require teams to document inbound dependencies, external APIs, DNS, metrics, backup and administrative paths. Use policy-as-code checks to catch broad selectors, missing policy types and unexpected open ports. Keep exceptions tied to an owner and an expiry date, and review them when workloads move or change labels.
FutureTechie’s related guides cover Kubernetes secrets management, Kubernetes autoscaling and container image security. Network isolation works best alongside those controls: secrets protect credentials, image hygiene reduces vulnerable software, and autoscaling keeps capacity predictable.
Conclusion
Kubernetes NetworkPolicy provides a practical way to replace unrestricted pod-to-pod communication with explicit, reviewable paths. The safest approach is to verify CNI support, map real application flows, add DNS and service-specific allows, test both permitted and denied traffic, and then roll out default-deny isolation gradually. Treat policies as part of application architecture rather than a one-time YAML exercise, and keep network restrictions paired with authentication, encryption and runtime monitoring.





