← Back to blogs

Kubernetes Network Policy Explained for Platform Teams

September 9, 2026CloudCops

kubernetes network policy
kubernetes security
CNI comparison
network segmentation
policy as code
Kubernetes Network Policy Explained for Platform Teams

A deployment passes CI, the pods start, and the application appears healthy. Then a developer discovers that a workload can reach an internal service it was never meant to contact, or an outbound connection appears during a compliance review with no clear explanation. The team has plenty of NetworkPolicy objects in Git, but nobody can confidently say which rules are enforced, which flows are allowed, or whether the observed traffic matches the intended design.

That gap between policy adoption and policy assurance is where many Kubernetes environments become difficult to operate. A Kubernetes network policy gives platform teams a native way to restrict pod traffic, but the object alone isn't proof of protection. Enforcement depends on the CNI, selector behavior, policy composition, testing, and observability. Production security comes from validating the complete path, not from counting YAML files.

Why Your Cluster Traffic Needs Guardrails

A common incident starts without an obvious exploit. A pod runs with broad outbound access, a dependency resolves to an unexpected endpoint, and the workload establishes a connection that nobody designed or reviewed. The first signal might be an alert from an egress monitor, a suspicious flow in a packet trace, or an auditor asking why a service can communicate with a namespace outside its documented trust boundary.

Kubernetes doesn't automatically create application-level segmentation. Without effective restrictions, pods can communicate across the cluster according to the capabilities of the surrounding network and services. Outbound access also remains broadly available unless a control blocks it. That default is convenient during development, but it becomes a liability as teams add namespaces, shared services, third-party integrations, and workloads with different sensitivity levels.

A conceptual illustration representing Kubernetes security with a pod connecting to an external endpoint during compliance audit.

The cost of unrestricted east-west traffic

Uncontrolled traffic creates several operational problems at once:

  • Security exposure: A compromised pod may probe databases, queues, metadata services, or administrative endpoints that should be unreachable.
  • Compliance uncertainty: A team may have documented segmentation while the live datapath permits more communication than the documentation describes.
  • Noisy neighbors: A faulty or overactive workload can consume shared service capacity because the cluster doesn't enforce meaningful communication boundaries.
  • Incident ambiguity: Responders can't quickly distinguish an expected dependency from an accidental path when policy intent isn't explicit.

A NetworkPolicy lets you express allowed communication around pods, namespaces, IP blocks, and ports. The model is intentionally focused on traffic relationships rather than individual application processes. That makes it useful as a baseline control for microsegmentation, but it also means teams must combine it with identity, application-layer controls, and telemetry where the risk demands more context.

Practical rule: Treat a policy object as a proposed control until you've verified that the CNI enforces it and that real traffic behaves as designed.

Kubernetes NetworkPolicy reached a major stability milestone in version 1.7, when it moved into the networking.k8s.io/v1 API group and became the stable built-in standard for pod-level traffic control, as documented in the Kubernetes 1.7 release notes. That history matters operationally. This isn't an experimental add-on that production teams can ignore. It's a foundational primitive, and leaving it unused allows every future service and dependency to expand the blast radius.

Understanding the NetworkPolicy Model and Semantics

Think of a NetworkPolicy as a label-driven firewall attached to a set of pods. The policy's podSelector identifies the protected workloads. Its ingress and egress rules describe which sources or destinations are permitted, and policyTypes states which traffic directions the policy governs.

Start with the selected pods

A policy without a useful selector doesn't express useful intent. An empty podSelector selects every pod in the policy's namespace, which is the usual building block for namespace-wide isolation.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: protect-database
  namespace: payments
spec:
  podSelector:
    matchLabels:
      app: database
  policyTypes:
    - Ingress

This policy applies to pods labeled app: database in payments. It doesn't automatically allow traffic. Once ingress isolation applies, only traffic allowed by applicable ingress rules can reach those pods.

Select sources and destinations carefully

A podSelector in an ingress from clause selects pods in the policy's namespace. A namespaceSelector selects namespaces by label. To select particular pods in particular namespaces, place both selectors in the same list entry.

ingress:
  - from:
      - namespaceSelector:
          matchLabels:
            team: checkout
        podSelector:
          matchLabels:
            app: api
    ports:
      - protocol: TCP
        port: 5432

The indentation is significant. A namespace selector and pod selector under one from item mean “these pods in these namespaces.” Separate list items mean alternatives. That YAML distinction is a frequent source of accidental over-permission.

Understand isolation before adding allows

Kubernetes uses default-isolation semantics. If a selected pod has an empty ingress list, ingress is denied. If it has an empty egress list, egress is denied. The direction becomes isolated when a matching policy declares that direction in policyTypes.

The building-access analogy is useful. A pod with no applicable policy is like a room without an access-card system. Once a policy selects it for ingress or egress, the room becomes restricted, and the allow rules define the cards that work. Multiple policies are additive. They don't run in priority order, and a later policy can't subtract an allow created by another policy.

A connection also needs both sides to permit it. The source pod's egress policy must allow the destination, and the destination pod's ingress policy must allow the source. This is why testing only from one side can produce misleading conclusions.

Keep the layer four boundary visible

The core Kubernetes model operates at layer 4, covering TCP, UDP, and optionally SCTP, as described in the Kubernetes NetworkPolicy documentation. It can control addresses, selectors, and ports, but it doesn't understand an HTTP route, a JWT claim, a TLS identity, or a database query.

That limitation isn't a defect in a basic network control. It defines where the control belongs. Use NetworkPolicy for coarse network reachability, then use ingress controllers, service meshes, application authorization, or CNI-specific extensions when decisions require application context.

One final prerequisite is easy to miss. The API server can accept a NetworkPolicy object even when the installed CNI doesn't implement enforcement. In that situation, the YAML exists, but traffic control doesn't happen.

Comparing CNI Implementations for Policy Enforcement

The CNI determines how policy becomes a datapath decision. That choice affects throughput under rule pressure, visibility into denied traffic, support for richer controls, and the amount of specialist knowledge your team needs to maintain the system.

Calico is commonly used with iptables-based enforcement and offers a mature policy ecosystem. It can be a practical fit when teams already operate Calico, need familiar Kubernetes semantics, and have a strong operational model around iptables and flow visibility. Calico also has extensions beyond the base API, but those features should be evaluated against portability requirements.

Cilium uses eBPF-based datapath capabilities and provides deep observability through tools such as Hubble. Its policy model can extend into application-aware controls, depending on the deployed feature set. The trade-off is a larger learning surface and a stronger dependency on eBPF-compatible kernel and platform behavior.

Cloud-provider CNIs and simpler implementations may support the Kubernetes API while exposing fewer policy-specific diagnostics or advanced capabilities. kube-router and other iptables-oriented options can be appropriate for focused environments, but rule growth and connection churn deserve deliberate testing rather than assumptions.

CNIEnforcement ModelL7 PolicyPerformance at ScaleObservability
CalicoCommonly iptables, with additional datapath options depending on deploymentAvailable through CNI-specific capabilitiesCan require careful tuning as rule volume growsPolicy and flow visibility depend on selected components
CiliumeBPF-based enforcementAvailable through Cilium policy featuresStrong fit for high policy density and dynamic workloadsHubble provides rich flow and policy visibility
kube-routerPrimarily iptables-orientedLimited in the base modelRule processing requires validation under churnOperational visibility depends on surrounding tooling
Cloud-provider CNIProvider-specific datapathVaries by provider and add-onsValidate against the provider's documented behaviorOften integrated with provider telemetry

The performance distinction is concrete. Independent benchmark reporting cited in the eBPF and iptables NetworkPolicy comparison describes eBPF-based Cilium sustaining 8.9 Gbps under complex L3/L4 policy and staying within about 10% of baseline under high pod concurrency. The same report describes iptables-based CNIs losing 60% to 70% throughput in comparable high-load conditions. Those figures are benchmark-specific, not a promise for every cluster, but they illustrate why enforcement architecture matters.

L7 inspection adds another trade-off. Deep inspection can sharply reduce throughput, so reserve it for high-value paths where application context justifies the cost. Don't move every connection into L7 processing because the feature exists.

Switch or extend

Switching CNIs can make sense when the current datapath lacks required observability, cannot meet tested performance needs, or leaves a compliance control unverifiable. It also creates migration risk, operational retraining, and possible incompatibilities with load balancing, routing, or cloud integration.

Extending the existing CNI is usually safer when the base enforcement is reliable and the missing capability is narrow. Start with flow logs, policy simulation, and CI validation before replacing a working datapath. Teams evaluating broader cloud networking patterns can also use the cloud networking engineering guidance as part of that architecture review.

Practical YAML Patterns and Testing Techniques

A reliable rollout starts with a namespace-wide baseline, then adds narrowly scoped exceptions. Apply the baseline only after identifying required platform dependencies, especially DNS and telemetry paths, because a deny-all egress rule can make otherwise healthy workloads appear broken.

Lock down the namespace first

This policy selects every pod in payments and isolates both directions:

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

The empty selector means all pods in that namespace. The absence of ingress and egress rules means no traffic is allowed by this policy. Add explicit allow policies afterward.

For same-namespace communication, use an empty podSelector in the peer entry. Because the policy is in payments, this allows traffic from pods in payments, not from every namespace:

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

That pattern is useful for transitional workloads, but it isn't least privilege. Replace it with application-specific labels when the dependency map is known.

Allow DNS and a controlled egress path

Egress restrictions often fail because teams remember the external dependency but forget name resolution. A policy can allow DNS to pods labeled as the cluster DNS service, then separately allow the required external CIDR and port.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-egress
  namespace: payments
spec:
  podSelector:
    matchLabels:
      app: api
  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
    - to:
        - ipBlock:
            cidr: 203.0.113.0/24
      ports:
        - protocol: TCP
          port: 443

The external CIDR is illustrative policy structure, not a recommendation for a real endpoint. In production, confirm how the CNI and cloud networking path handle destination rewriting before relying on ipBlock behavior.

A list of four essential Kubernetes YAML patterns for managing network traffic policies and connectivity.

Test behavior, not object presence

Deploy a temporary diagnostic pod with the same labels and namespace as the workload. From it, use kubectl exec with curl for HTTP services and nc for TCP connectivity. Test an expected allow path, an expected deny path, DNS resolution, and the return path from the destination. A successful kubectl get networkpolicy command proves only that the API object exists.

Useful checks include:

  • Inspect selectors: Run kubectl describe networkpolicy and compare selectors with the labels present on pods and namespaces.
  • Test both directions: Confirm source egress and destination ingress independently.
  • Observe flows: Use the CNI's flow visibility or policy simulation features to identify which rule matched.
  • Gate changes in CI: Parse manifests, check required policyTypes, detect broad selectors, and require an explicit review for new external destinations.
  • Promote gradually: Apply policies in a lower environment, compare expected and observed flows, then promote with documented exceptions.

The video below demonstrates practical policy testing and simulation techniques.

Best Practices for Platform Teams at Scale

At scale, policy management becomes a product problem. Developers need a predictable way to request connectivity, platform engineers need enforceable guardrails, and security teams need evidence that the rules match the approved design.

Start every namespace with a default-deny baseline, but don't stop there. A baseline without a tested onboarding path creates emergency exceptions and encourages teams to disable controls. Publish reusable policy examples for common dependencies such as DNS, ingress gateways, metrics collection, and service-to-service calls. Give application teams a clear method to add narrowly scoped rules without editing platform-owned controls.

Separate ownership from authority

Platform-owned policies should establish minimum protections. Application teams should own the rules that describe their service's legitimate dependencies. Keep both in version control, but make ownership visible through metadata labels and repository structure.

A policy review should answer practical questions:

  • What workload is selected? Check the exact labels and namespace.
  • What direction is isolated? Require explicit policyTypes.
  • Which dependency is allowed? Prefer named labels and namespace labels over broad ranges.
  • What evidence supports the rule? Link the change to observed traffic or an approved architecture decision.
  • How will the rule be removed? Give temporary exceptions an owner and expiry process.

OPA Gatekeeper and Kyverno can enforce structural standards, such as requiring policies in new namespaces or rejecting unapproved selectors. CI can validate YAML syntax, render Helm or Kustomize output, and run reachability checks before deployment. These checks don't replace runtime verification, but they catch malformed or overly broad changes before they reach a live datapath.

Make exceptions deliberate

Temporary access requests should use a ticket, pull request, or similar auditable workflow. Don't accept a direct production edit as the normal path. A useful exception records the source, destination, port, business reason, approver, owner, and review date.

Teams adopting this model can use policy-as-code practices for Kubernetes to structure repository reviews, admission controls, and audit workflows. The important outcome isn't a particular tool. It's a repeatable system where policy changes are reviewed like application code and validated against live behavior.

Troubleshooting and Compliance in Enterprise Environments

When a policy appears ineffective, begin with the enforcement path, not the YAML formatting. Confirm that the installed CNI implements NetworkPolicy, identify the component responsible for programming rules, and inspect its logs for rejected or delayed updates. The Kubernetes API won't tell you that a policy was accepted but ignored by an unsupported datapath.

Selector errors are the next common failure. Check pod labels with kubectl get pods --show-labels, inspect namespace labels, and compare the rendered manifest with the object stored in the cluster. A selector that points at app: frontend won't match a deployment using app.kubernetes.io/name: frontend. A namespace selector and pod selector placed as separate list entries also create an OR relationship, which may allow far more traffic than intended.

Read the effective result

Network policies combine additively. Adding a restrictive policy doesn't cancel an existing allow, and policy order doesn't create priority. Trace the complete set of policies selecting the source and destination, then evaluate the connection at both ends.

Use the CNI's flow logs or visualization interface to answer four questions:

  1. Which pod initiated the connection?
  2. Which destination and port did it use?
  3. Which policy decision allowed or denied the flow?
  4. Did a Service, node route, load balancer, or address rewrite change what the policy evaluated?

Host-network pods and rewritten source addresses can produce results that differ from a simple pod-to-pod test. Test the actual production path, including ingress and egress gateways where applicable.

Build evidence auditors can use

A compliance program needs more than exported YAML. For controls aligned with ISO 27001, SOC 2, or GDPR, retain versioned policy manifests, review history, namespace ownership, test results, and flow evidence showing that restricted paths are denied. Document the intended communication matrix and record approved exceptions.

A regular audit should flag namespaces without a baseline, workloads with unrestricted egress, broad namespace selectors, and policies that haven't been exercised since deployment. Pair configuration scans with runtime telemetry because an apparently narrow rule can still fail if labels drift or the CNI interprets the path differently than expected.

A structured Kubernetes security posture management approach can connect configuration findings, runtime observations, and remediation ownership. That connection is what turns a compliance screenshot into an operational control.

Closing the Gap Between Adoption and Assurance

NetworkPolicy is widely deployed, but deployment alone doesn't establish assurance. A recent community survey signal reported that 83% of Kubernetes teams use network policies, while 60% still don't fully understand what those policies are doing in practice. The same source reported that 42% validate policies with observability tools, as described in the community survey signal. The operational message is clear: adoption is ahead of verification.

The native model remains valuable, but it works at the IP and port level with label selectors. Teams increasingly ask for DNS-based selectors, policy ordering, native audit logging, and cross-cluster enforcement. AI infrastructure, dynamic service meshes, and multi-cluster services expose those gaps because endpoint identity and application context can change faster than static rules.

Use CNI-specific extensions, service mesh controls, and observability tooling where native semantics stop short. Keep the base Kubernetes policy understandable and portable, then add richer controls only where their operational cost is justified.

Audit your current policies now. Verify enforcement with controlled allow and deny tests, connect runtime flow data to policy reviews, and assign owners to every exception. Then document which workloads will need application-aware or multi-cluster controls as your platform evolves.


CloudCops GmbH helps platform teams design and operate Kubernetes security controls with policy-as-code, GitOps workflows, observability, and compliance-oriented audit evidence. Visit CloudCops GmbH to discuss how to validate NetworkPolicy enforcement and build a governed workflow for your clusters.

Ready to scale your cloud infrastructure?

Let's discuss how CloudCops can help you build secure, scalable, and modern DevOps workflows. Schedule a free discovery call today.

Continue Reading

Read Kubernetes Security Posture Management: Practical Guide
Cover
Jul 4, 2026

Kubernetes Security Posture Management: Practical Guide

Learn Kubernetes Security Posture Management (KSPM). Detect misconfigurations, implement policy-as-code, and build a mature K8s security posture.

kubernetes security posture management
+4
C
Read Zero Trust Architecture: A Guide for Cloud-Native Teams
Cover
Jun 26, 2026

Zero Trust Architecture: A Guide for Cloud-Native Teams

Implement a robust Zero Trust Architecture in your cloud-native stack. Our guide covers principles, Kubernetes patterns, a migration roadmap, and compliance.

zero trust architecture
+4
C
Read What Is OPA? A Guide to Policy-as-Code
Cover
Jun 2, 2026

What Is OPA? A Guide to Policy-as-Code

Curious about what is OPA? This guide explains Open Policy Agent, Rego, and how to use policy-as-code for Kubernetes, CI/CD, and API security.

what is opa
+4
C