Kubernetes network policies

Kubernetes network policies segment pod traffic inside a self-managed cluster, but only when the network plugin enforces them. This page covers the design, setup, limits and testing work behind them.

On this page

Why Kubernetes network policies need design work before rollout

By default, pods in a Kubernetes cluster can reach each other across namespaces, and nothing in the API stops that. A NetworkPolicy object selects pods and states which ingress and egress traffic they accept, but the object only has effect when the cluster's network plugin enforces it. Enforcement depends on the CNI plugin, so a policy that applies cleanly with kubectl apply can still allow every connection if the installed plugin ignores it. Confirm enforcement support in your chosen plugin's documentation before writing a single policy.

Teams usually need segmentation when a compliance assessment asks how workloads are isolated, when a regulated application shares a cluster with other tenants or teams, or when a breach in one service should not give an attacker a path to a database or identity system. The work covers more than writing YAML. It includes mapping which namespaces and workloads talk to which, deciding where the default deny starts, identifying DNS, metrics, admission webhooks and node traffic that policies must still allow, and agreeing on who owns policy changes. Ask your team to produce a traffic inventory from a running cluster before any policy is enforced.

Rollout is where most segmentation efforts break. A default deny applied to a namespace that still depends on undocumented flows will cut off a service that appeared healthy during testing. Plan a staged rollout: apply policies in a non-production cluster that mirrors your CNI and workloads, observe dropped connections through your plugin's logs or flow tooling, and add allow rules deliberately. Record each exception with an owner and a reason, since auditors and your own security team will ask why a path exists. The effort depends largely on how many applications share the cluster and how well their traffic is already documented.

Choosing a network plugin that enforces NetworkPolicy

NetworkPolicy objects are accepted by the API server whether or not the cluster's network plugin enforces them, so a cluster can look segmented while allowing all traffic. The cards below cover the questions to settle about the CNI in use before writing any policy, and each one should be confirmed against the plugin's own documentation.

Confirm enforcement is actually active

The API server stores NetworkPolicy objects without checking whether anything acts on them. Some CNI plugins enforce the full API, some enforce only part of it, and some do not enforce it at all. Ask the plugin vendor or project which policy fields it enforces in your version, and test with a deny-all policy that a pod can no longer reach a neighbor. Treat a successful apply as proof of nothing.

NetworkPolicy docs

Check egress and ingress support

Ingress rules control traffic into pods, and egress rules control traffic leaving them. Egress control is often the gap that matters most for data exfiltration and lateral movement, yet some plugins enforce ingress only. Confirm both directions separately, including rules that select external IP blocks and DNS traffic, because a default deny on egress will break name resolution unless DNS is allowed explicitly.

Verify logging of denied flows

When a policy blocks a connection, the application usually sees only a timeout. Some plugins can log dropped or allowed flows, which turns troubleshooting and audit evidence into a search instead of guesswork. Ask whether the plugin records denied connections, where those logs are written, how long they are kept, and whether they can be forwarded to your log platform without custom tooling.

Assess node-level and host policy

Standard NetworkPolicy applies to pods, not to host processes, node ports or traffic that a node itself sends. If the threat model includes compromised nodes or host networking workloads, check whether the plugin offers a separate cluster-wide or node-level policy resource, and confirm how that resource interacts with NetworkPolicy ordering and precedence. Document which resource is authoritative for each rule.

Confirm behavior with your Kubernetes version

Plugin support for NetworkPolicy fields often depends on the plugin release and the cluster's Kubernetes minor version. Because the project supports a limited set of minor versions at a time, plugin and cluster upgrades should be planned together. Record the exact plugin version, the Kubernetes version and the supported feature list in your platform documentation, and repeat the enforcement tests after each upgrade.

Configuration options and when each fits

This table compares the NetworkPolicy building blocks most teams combine: default deny rules, namespace and pod selectors, ipBlock CIDR rules and named ports. Read each row for the situation where it fits and the cost it carries, such as label upkeep or DNS being blocked during egress lockdown. Most clusters use several of these together rather than picking one.

OptionWhen it fitsTrade-off
Default deny ingressEvery namespace that should accept only traffic someone has explicitly approved, as a baseline before allow rules are addedApplications break at once if allow rules for health checks, ingress controllers or monitoring scrapers are missing
Default deny egressWorkloads handling regulated data where outbound connections must be limited to named destinationsDNS lookups fail unless UDP and TCP port 53 to the cluster DNS service are allowed, so test this rule first
Namespace selectorsAllowing traffic between whole environments or teams, such as monitoring or ingress namespaces reaching application namespacesBroad rules can admit every pod in a namespace, and namespace labels must be set and kept consistent
Pod selectorsFine-grained rules between tiers, such as a web pod reaching only its database pods on one portLabel-based rules need maintenance; a mislabeled pod is either blocked or silently admitted
ipBlock rulesReaching external systems at fixed address ranges, such as a corporate database or a payment provider's published rangePod IPs change, so ipBlock suits stable external ranges, not traffic between pods; confirm how your plugin treats cluster and node addresses
Named portsPolicies that follow a port name declared on the container, so a port number change does not require rewriting every ruleOnly works when containers declare the port name; undeclared names silently match nothing, so check manifests during testing

How to roll out network policies in a cluster

This sequence moves a cluster from open pod-to-pod traffic to enforced segmentation in controlled stages, so each change is verified before the next one widens the scope.

  1. Confirm the CNI enforces NetworkPolicy

    Before writing any policy, confirm that the network plugin in your cluster actually enforces NetworkPolicy objects. Some plugins accept the objects but do not enforce them, so a policy can look applied while traffic still flows. Check the plugin's documentation for its NetworkPolicy support and for any features it adds beyond the standard API, and confirm the version your distribution ships. Done means you have a written answer from the plugin's documentation and a test in a throwaway namespace: apply a deny rule, confirm a connection between two pods is blocked, then remove the rule.

  2. Label namespaces and workloads consistently

    Policies select traffic by labels, so labels must be designed before rules are written. Agree on a small set of keys, such as an environment label, a team or owner label and an application label, and apply them to every namespace and to the pod templates of every workload. Enforce the convention in your deployment tooling or admission checks so new workloads inherit it. Done means a query of namespaces and pods shows the expected labels on all of them, with no unlabeled workloads left in scope.

  3. Inventory existing traffic flows

    Before blocking anything, record what currently talks to what. Use your monitoring data, service and ingress definitions, and the flow logs or observability tooling your network plugin provides, if it offers them. Note cluster DNS, the API server, shared databases, message brokers, monitoring scrapers, ingress controllers and any traffic that leaves the cluster. Confirm these flows with the application owners, since undocumented dependencies are the most common cause of outages during rollout. Done means a flow list for each namespace that the team has reviewed.

  4. Apply default deny in a staging namespace

    Choose a non-production namespace with representative workloads and apply a default deny policy for ingress and egress that selects all pods. Expect immediate breakage of DNS lookups and any service that depends on the flows you inventoried. Watch application logs and the connection failures they report. Done means the namespace is isolated as intended and you have a list of every flow that broke, which becomes the input for the allow rules in the next step.

  5. Add allow rules for DNS and required paths

    Add the smallest set of allow rules that restores the flows from your inventory. Start with DNS to the cluster DNS service on port 53 over UDP and TCP, then add explicit ingress from the ingress controller and from known clients, and egress to each named dependency by pod or namespace selector and port. Prefer selectors over IP ranges where possible. Done means a blocked connection, such as a pod reaching an unlisted service, still fails, and every inventoried flow works. Keep both results as test evidence.

  6. Test blocked and allowed connections

    Turn the checks from the previous steps into a repeatable test. From a source pod, attempt connections that the policy should block and confirm they time out or are refused. Attempt the flows that should be allowed and confirm they succeed. Include a check for egress to an external address if external egress is restricted. Run the same tests after each policy change. Done means a script or documented procedure produces a pass or fail result per flow, and the team can rerun it on demand.

  7. Expand policy namespace by namespace

    Repeat the inventory, default deny and allow rule cycle for each remaining namespace, starting with those of lower risk and fewer dependencies. Keep rollout records per namespace, including the flows tested and who approved them, and roll back a policy quickly if a production dependency breaks. Once every namespace has a policy, review the cluster for pods that still lack coverage. Done means every namespace in scope has a default deny policy, documented allow rules and passing connection tests, and the rollout record is kept for audit and future changes.

How policies filter pod traffic

The diagram starts with a pod sending a request to another pod and follows it through the CNI plugin, which is the enforcement point. The plugin evaluates the policies that select the destination pod, matching namespace and pod labels for each direction. The same check applies to the sender's egress rules and the receiver's ingress rules, so a request must pass both. Check that your chosen plugin actually enforces NetworkPolicy, because a plugin that does not will accept the objects and still allow everything.

Pod traffic is checked against egress and ingress rules at the CNI plugin.

Controlling egress traffic from pods

Egress policies are harder to get right than ingress policies because a pod's outbound calls depend on services it rarely thinks about. Before writing any egress rule, inventory every destination a workload reaches, including cluster DNS, the Kubernetes API server, package and image sources, object storage, message brokers, and databases that may sit outside the cluster. Build this list from observed traffic in a staging or audit period rather than from memory, and confirm each destination with the application owner. Do not assume a particular set of endpoints is required for your workloads until your own traffic data or the vendor documentation confirms it.

Once the inventory exists, express each destination with the selector that fits it. Inside the cluster, use namespaceSelector and podSelector under egress.to so rules follow labels rather than changing pod IPs. For services outside the cluster, use ipBlock with a CIDR, and keep those blocks as narrow as the provider or data center allows. Remember that ipBlock matches addresses, so a DNS name or a load balancer that changes addresses will need a review cadence. Also check whether your CNI plugin supports DNS-aware or FQDN-based rules, because the built-in NetworkPolicy resource does not match on hostnames. Confirm this capability with the plugin documentation before you rely on it.

A missing allow rule usually fails quietly. A pod with a default deny egress policy may show DNS timeouts, slow startup, failed image pulls, or application errors that look like an unrelated outage, so an incident team can spend hours chasing the wrong layer. Allow DNS to the cluster resolver first and test name resolution from inside the pod, then add each remaining destination and test it with the same pod identity. Run the check in a non-production namespace, and keep a documented rollback so the owning team can remove a rule quickly if a dependency was missed.

Testing that policies do what they say

A manual check runs a test pod in a chosen namespace and attempts connections to other pods, services and external addresses, then compares the result with the policy you intended. It is the fastest way to confirm that a newly applied default deny rule blocks traffic and that an allow rule opens only the ports you listed. It shows what the cluster does right now for the source and destination you picked, and nothing more.

  • Source and destination pairs: Test from each side of every rule, including pods in other namespaces, because an ingress rule on one pod says nothing about egress from another.
  • Ports and protocols: Test the exact port listed in the policy and a neighboring port, so an overly broad rule is visible.
  • DNS and external egress: Check name resolution and outbound addresses separately, since egress policies often block DNS by accident.
  • Label state: Confirm the test pod carries the labels the selector expects, because a mislabeled pod will fail or pass for the wrong reason.
  • Gaps: Manual checks miss traffic from source pods you did not think to test, rules that apply only after a pod restarts, and drift that happens later.

Before relying on any manual result, confirm with your CNI vendor or documentation that the plugin enforces NetworkPolicy and that the test image and tools behave as expected in your cluster.

Security and operational risks to plan for

Network policies fail in ways that rarely show up as errors. A policy can exist and still do nothing, a default deny can break cluster plumbing, and a label change can reopen a path nobody meant to open. The controls below tie each risk to a check you can run before and after rollout.

Policies that enforce nothing

A NetworkPolicy object is accepted by the API server even when the installed network plugin does not enforce it. Traffic then flows as if no policy existed, and the object looks correct in kubectl get networkpolicy. Confirm that your CNI plugin enforces NetworkPolicy, then test a known-denied flow from a pod in each namespace and record the result as an acceptance check before any policy is treated as protection.

NetworkPolicy docs

Default deny that blocks plumbing

A default deny ingress or egress policy also cuts off DNS lookups to the cluster resolver, kubelet health probes, metrics scraping and calls to the API server from controllers. Workloads then fail in ways that look like application bugs. Before applying default deny, list the flows each namespace needs for DNS, probes, metrics and the API server, and allow them explicitly in the same change.

Label drift that opens paths

Pod and namespace selectors match on labels, so a changed or missing label can silently widen or narrow who can reach a workload. A chart upgrade that renames a label, or a team that adds env=prod to a test pod, can move traffic across a boundary. Run a drift check that compares live labels against the labels the policies select on, and alert when a selector matches a pod it did not match before.

Policies left behind by changing workloads

Policies written for an application at one release often outlive the design they assumed. New sidecars, added ports, moved databases or a new external API each need a matching rule, and removed services leave allow rules that no longer serve a purpose. Make policy changes part of the workload review, require an owner for each policy, and re-review policies on a fixed schedule set by your change process.

Egress allowances nobody audits

Egress rules are often written broad, such as allowing all external HTTPS, because the exact destinations are hard to list. Those rules become a path for data leaving the cluster and for compromised pods to reach command servers. Record which destinations each namespace actually uses from flow logs, replace broad CIDR allowances with named destinations where the plugin supports it, and review the allowed flow list on the same cadence as access reviews.

Testing that never runs again

A policy test that passed at rollout says nothing about the cluster after the next upgrade, plugin change or namespace move. Keep a set of expected-allowed and expected-denied connections as code, run it in the pipeline that changes policies and after cluster upgrades, and store the results as evidence for internal reviewers and assessors. Confirm with your plugin vendor which flow logs or policy audit events it can export.

Questions teams ask before rolling out network policies

How much effort does a NetworkPolicy rollout take?

Effort depends mostly on how much traffic in your clusters is already understood. A cluster where every service-to-service flow, database connection and external API call is documented can be segmented in a fraction of the time of one where flows are discovered only when something breaks. The main drivers are the number of namespaces, the number of applications that talk to each other, how many environments must be covered, and whether the CNI plugin already enforces policy. Ask any partner to break the estimate into traffic discovery, policy authoring, staged rollout and testing, since each phase scales differently.

What drives the cost of segmenting several clusters?

Cost is mostly labor, paid either to your own engineers or to a partner under a written scope. The cost rises with cluster count, namespace count, the number of distinct applications, and the amount of undocumented traffic, because undocumented flows take time to find and verify. One-time work includes discovery, policy design, testing and rollout. Recurring work includes reviewing policies when new services are added and keeping staging aligned with production. When you request a quote, ask for the per-cluster breakdown, the assumptions about existing documentation, and what happens if discovery finds more flows than expected.

Can our internal platform team roll out network policies alone?

Often yes, if the team already runs the cluster networking stack, has experience writing NetworkPolicy objects and can test in a non-production cluster. The harder parts are usually not the YAML. They are finding every flow that application owners forgot to mention, deciding default deny behavior for each namespace without breaking shared services such as DNS and monitoring, and keeping the rollout inside change windows. If your team lacks time or has not operated policy enforcement before, an outside partner can take on discovery and testing while your engineers keep ownership of the final policies.

What do we need to provide for the work?

You need to provide named traffic owners for each application, access to a staging cluster that mirrors production networking, and agreed change windows for enforcement. Traffic owners confirm which flows are legitimate, including those that happen only during batch jobs or failover. A staging cluster lets you find broken flows before users do. Change windows matter because enforcement can block traffic immediately, so you need an agreed rollback path and people available to respond. Also provide read access to existing manifests, Helm values, and any service mesh or ingress configuration that affects traffic.

How long does a rollout take for different scopes?

Duration follows scope. A single cluster with a small number of namespaces and documented traffic takes far less time than a multi-cluster estate with many teams and little documentation. Plan separately for discovery, which is often the longest phase, policy authoring, staged enforcement in staging and production, and post-rollout review. Ask for a schedule that shows which phases depend on traffic owner responses and change windows, because those dependencies usually set the calendar. DeployOpen does not publish a fixed duration, so the timeline comes from the written scope for your environment.

Does a fixed-scope engagement fit a network policy project?

A fixed-scope engagement fits well when the boundaries are clear: which clusters, which namespaces, which traffic categories, and which deliverables such as policy manifests, test results and a runbook. Most DeployOpen engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts. Discovery findings can change the picture, so agree in advance how newly found flows will be handled, whether through a change request or a defined allowance. Ongoing policy review and continuous testing can be handled as a retainer after the initial rollout.

What breaks most often when default deny is applied?

The most common failures are traffic that nobody documented: DNS lookups to CoreDNS, metrics scraping from Prometheus, health checks from load balancers or kubelets, and calls to external APIs that use IP addresses rather than names. Egress policies also tend to break package downloads, certificate validation and time synchronization if they are applied too broadly. To catch these, test each namespace in staging with default deny applied, watch dropped traffic where your CNI exposes that signal, and confirm each flow with its traffic owner before production enforcement. Check your CNI documentation for the exact logging and policy features it provides.

How DeployOpen works on this

DeployOpen plans, implements, hardens, documents and supports self-hosted open-source platforms inside infrastructure you control, including Kubernetes clusters in your cloud accounts, data centers or air-gapped networks. For network policy work, that means agreeing the traffic model in writing first, then building and testing policies against your own cluster and handing over the documentation your teams need to run them.

How we scope

  • Inventory the namespaces, workloads and traffic flows that policies must cover, and confirm which CNI plugin your cluster already runs.
  • Agree in writing which default deny patterns, egress destinations and DNS rules are in scope for each environment.
  • Confirm who owns policy changes after handover, including application teams, platform engineers and security reviewers.

How we build

  • Apply default deny baselines per namespace, then add allow rules driven by namespace and pod selectors that match your labeling scheme.
  • Design egress controls for external services, cluster DNS and the API server, recording each allowed destination and its owner.
  • Test every policy in a non-production cluster first, checking that expected traffic still flows and that denied traffic is actually blocked.

How we hand over

  • Deliver policy manifests in version control with a short guide explaining each rule, its purpose and the workload it protects.
  • Provide test scripts and a verification record showing allowed and denied connections for each namespace in scope.
  • Walk your platform and application teams through adding a new workload, reviewing a policy change and rolling back a faulty rule.

How we support

  • Ongoing support, policy reviews and continuous testing are available as a retainer, based on the written scope.
  • Retesting after Kubernetes upgrades or CNI changes, since plugin behavior and supported policy fields can change between versions.
  • Written quotes follow from the agreed scope, so you can see which work is one-time and which recurs before you commit.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.