Kubernetes Network Policy

Kubernetes Network Policy: Code Example and Best Practices

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:

Why Are Kubernetes Network Policies Important?

Kubernetes network policies are a crucial tool for managing and securing applications deployed in a Kubernetes cluster. Important capabilities include:

  • Security: Network policies provide an additional layer of security by controlling network traffic within the cluster, allowing you to define what traffic is allowed to reach your pods and prevent unauthorized access.
  • Network segmentation: Network policies allow you to segment your network, isolating parts of your application and controlling the flow of network traffic between different parts of the cluster.
  • Compliance: Network policies can be used to enforce organizational or regulatory compliance requirements, such as separating sensitive data and limiting access to it.
  • Resource optimization: By controlling network traffic, network policies can be used to optimize resource utilization and minimize network congestion.

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 policy includes the podSelector element to select the pod group that the policy covers—for instance, the below example applies to pods with the db role. If the selector is empty, it will select every pod in the namespace by default.

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:

kind: NetworkPolicy
name: example-policy
namespace: default
role: db
- Ingress
- Egress
- from:
- ipBlock:
- namespaceSelector:
project: exampleproject
- podSelector:
role: frontend
- protocol: TCP
port: 6379
- to:
- ipBlock:
- 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:

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 to except for the range between to

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 and on port 5978.

Related content: Read our guide to Kubernetes security policy

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 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.


  • 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:

Join our mailing list​

Get updates on blog posts, workshops, certification programs, new releases, and more!