Guides: Kubernetes Network Policy

Kubernetes Network Policy: Use Cases, Examples, and Tips [2025]

What is a Kubernetes Network Policy?

A Kubernetes network policy is a specification that defines how pods are allowed to communicate with each other and other network endpoints in a Kubernetes cluster. Network policies enable fine-grained control over network traffic, enabling network segmentation and security for your applications. They allow you to define inbound and outbound traffic rules for pods and are implemented using a CNI plugin, such as Calico or Weave Net, in the Kubernetes cluster.

This is part of a series of articles about Kubernetes security.

In this article:

8 Use Cases for Kubernetes Network Policies

Kubernetes network policies are versatile and support a variety of security and operational use cases:

  1. Isolating applications by namespace: Apply policies that restrict network access between different namespaces. This is useful for separating staging and production environments or for implementing multi-tenancy.
  2. Restricting ingress traffic to specific pods: Limit incoming traffic to only trusted sources, such as allowing only frontend pods to communicate with backend pods.
  3. Controlling egress traffic from sensitive workloads: Prevent sensitive applications from making outbound connections to unauthorized IP addresses or external services.
  4. Allowing traffic within an application tier: Enable communication between pods with the same labels, such as all pods in a database tier, while denying access from other tiers.
  5. Enforcing zero trust networking principles: Default-deny policies can be applied to all pods, requiring explicit allow rules. This aligns with the principle of least privilege.
  6. Implementing network-based compliance controls: Create policies that enforce data residency or access restrictions, helping meet regulatory requirements like PCI DSS or HIPAA.
  7. Protecting critical services: Shield critical services, such as authentication servers or databases, from unnecessary network exposure.
  8. Limiting external API access: Allow specific pods or services to access external APIs while blocking all others, reducing the attack surface.

How Do Kubernetes Network Policies Work?

Kubernetes network policies allow you to control the network traffic between pods in a cluster, providing an additional layer of security. These policies work by allowing you to define rules that control how pods communicate with each other and other network endpoints in a cluster. They are implemented using a Container Network Interface (CNI) plugin that is installed in the cluster.

The network policies are defined as Kubernetes objects, via a YAML manifest file that includes desired selectors, ingress and egress rules. Network policies are applied using the Kubernetes API. They can be created and updated using command-line tools or through the Kubernetes Dashboard.

How to define a network policy
There are different types of selectors that you can use to define the pods that are subject to the policy, such as CIDR blocks, pod selectors, and namespace selectors. These selectors allow you to target specific pods, namespaces, or network ranges for the policy.

It is important to note that network policies are additive, meaning that multiple policies are applied to a set of pods, rather than sequentially. This means that if multiple policies apply to the same set of pods, the policies are combined to form the final set of rules for that set of pods. If there are conflicts in the policies applied to related pods, the policies will not be enforced. For example, if two services have conflicting communication policies, they cannot connect to each other.

By default, Kubernetes includes a simple network plugin called kubenet, which provides basic network isolation and is suitable for simple use cases. However, more advanced network plugins can provide additional features such as network policies, which allow you to define and enforce network security policies.

Read our guide: Get started with Kubernetes network policy

Kubernetes Network Policy Example

This is based on an example shared in the Kubernetes documentation.

The NetworkPolicy spec contains the information required to define the network policy for a specific namespace. The mandatory fields for a NetworkPolicy, like other Kubernetes configurations, include:

  • apiVersion
  • kind
  • metadata

Every NetworkPolicy also has a policyTypes field that specifies if it applies to Ingress or Egress (or both). The default is Ingress, meaning that if this field is not specified, the policy will apply to ingress traffic to the selected pods, although egress rules will automatically apply to egress traffic:

  • Ingress rules: These determine the ingress traffic allowed by the NetworkPolicy. Rules apply to traffic that matches the specified ports and from elements.
  • Egress rules: These specify the traffic allowed based on the ports and to elements.

Here is an example of a NetworkPolicy:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: example-policy
namespace: default
spec:
podSelector:
matchLabels:
role: db
policyTypes:
- Ingress
- Egress
ingress:
- from:
- ipBlock:
cidr: 128.12.0.0/24
except:
- 128.12.46.0/16
- namespaceSelector:
matchLabels:
project: exampleproject
- podSelector:
matchLabels:
role: frontend
ports:
- protocol: TCP
port: 6379
egress:
- to:
- ipBlock:
cidr: 10.0.0.0/8
ports:
- protocol: TCP
port: 5978

In order to execute the above policy you will need to run the following command:

kubectl apply -f network.yaml

Where network.yaml contains the above YAML code. The output looks like this:

Command line output showing the successful creation of the example-policy network policy using the network.yaml file

This NetworkPolicy specifies that pods with the db role should be isolated. It specifies ingress rules to allow traffic to all pods labeled db via port 6379 (according to the TCP protocol). This includes traffic from the following sources:

  • Pods with frontend role.
  • Pods with project label exampleproject.
  • IP addresses within the specified ranges: from 128.12.0.0 to 128.12.255.255 except for the range between 128.12.46.0 to 128.12.46.255.

The example NetworkPolicy also includes egress rules that allow traffic from all pods within the default namespace labeled db to the addresses within the CIDR range 10.0.0.0/8 and on port 5978.

Related content: Read our guide to Kubernetes security policy

Understanding Kubernetes Network Policy Ingress/Egress Selectors

Ingress and egress selectors define the sources and destinations that are allowed to communicate with a given set of pods. Kubernetes network policies support three primary types of selectors: podSelector, namespaceSelector, and ipBlock.

podSelector

A podSelector targets specific pods within the same namespace based on their labels. This allows you to permit or deny traffic from particular pods that share defined attributes, such as:

podSelector:
  matchLabels:
    app: demo

This example allows or restricts traffic to pods labeled app: demo.

namespaceSelector

namespaceSelector applies rules to all pods within a namespace, based on namespace labels. This is useful for controlling access between namespaces:

namespaceSelector:
  matchLabels:
    app: demo

You can also reference a specific namespace by using Kubernetes’ default label:

namespaceSelector:
  matchLabels:
    kubernetes.io/metadata.name: demo-namespace

ipBlock

ipBlock allows or restricts traffic to and from specific CIDR IP ranges. This is typically used for external traffic, as pod IPs are ephemeral and not suitable for long-term rules:

ipBlock:
  cidr: 10.0.0.0/24

Combining Selectors

Selectors can be combined to define more complex rules. When multiple from blocks are defined under an ingress rule, they are evaluated using logical “or” logic:

- from:
    - podSelector:
        matchLabels:
          app: demo-api
    - namespaceSelector:
        matchLabels:
          app: demo

To enforce an “and” condition, both selectors are included under a single from block:

- from:
    - namespaceSelector:
        matchLabels:
          app: demo
      podSelector:
        matchLabels:
          app: demo-api

This rule applies only when both conditions are met—i.e., the pod has the demo-api label and is in a namespace labeled app: demo.

Port-Based Filtering

To restrict traffic further, ingress and egress rules can include port specifications. This limits traffic to required ports and protocols:

ports:
  - protocol: TCP
    port: 32000
    endPort: 32100

This example allows communication over TCP between ports 32000 and 32100. Omitting endPort restricts access to a single port.

Kubernetes Network Policy Best Practices

Here are some best practices for using Kubernetes Network Policy:

  • Start with a deny-all policy: Start by denying all network traffic and gradually allow only the necessary traffic as you identify it. This helps to reduce the attack surface and minimize the risk of a security breach.
  • Use labels to define policies: Use labels to define policies for pods and services, making it easier to manage and maintain policies as your cluster evolves over time.
  • Use namespace-level policies: Use namespace-level policies to restrict network traffic between namespaces and prevent pods in one namespace from accessing pods in another namespace.
  • Define explicit allow rules: Define explicit allow rules for traffic that should be allowed instead of relying on an implicit allow-all rule. This helps to ensure that you have a clear and secure network policy.
  • Use network segmentation: Use network segmentation to divide the network into smaller parts and limit the flow of traffic between segments. This helps to reduce the attack surface and minimize the risk of a data breach.
  • Regularly review and update policies: Regularly review and update policies to ensure that they are still relevant and effective in preventing security breaches.
  • Use network policy visualization tools: Use network policy visualization tools to help you understand and manage your network policies more effectively.

By following these best practices, you can effectively use Kubernetes Network Policy to improve the security of your Kubernetes cluster and reduce the risk of a security breach.

 

Kubernetes Security and Observability with Calico

Tigera’s commercial solutions provide Kubernetes security and observability for multi-cluster, multi-cloud, and hybrid-cloud deployments. Both Calico Enterprise and Calico Cloud provide the following features for security and observability:

Security

  • Security policy preview, staging, and recommendation – Easily make self-service security policy changes to a cluster without the risk of overriding an existing policy. Calico can auto-generate a recommended policy based on ingress and egress traffic between existing services, and can deploy your policies in a “staged” mode before the policy rule is enforced.
  • Compliance reporting and alerts – Continuously monitor and enforce compliance controls, easily create custom reports for audit.
  • Intrusion detection & prevention (IDS/IPS) – Detect and mitigate Advanced Persistent Threats (APTs) using machine learning and a rule-based engine that enables active monitoring.
  • Microsegmentation across Host/VMs/Containers – Deploy a scalable, unified microsegmentation model for hosts, VMs, containers, pods, and services that works across all your environments.
  • Data-in-transit encryption – Protect sensitive data and meet compliance requirements with high-performance encryption for data-in-transit.

Observability

  • Dynamic Service Graph – Get a detailed runtime visualization of your Kubernetes environment to easily understand microservice behavior and interaction.
  • Application Layer Observability – Gain visibility into service-to-service communication within your Kubernetes environment, without the operational complexity and performance overhead of service mesh.
  • Dynamic Packet Capture – Generate pcap files on nodes associated with pods targeted for packet capture, to debug microservices and application interaction.
  • DNS Dashboard – Quickly confirm or eliminate DNS as the root cause for microservice and application connectivity issues in Kubernetes.
  • Flow visualizer – Get a 360-degree view of a namespace or workload, including analytics around how security policies are being evaluated in real time and a volumetric representation of flows.

Next steps: