Guides

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

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.

Learn more in our detailed guide to Kubernetes network security

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:

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:

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 policies

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.

Enterprise Kubernetes Networking with Calico

Calico’s flexible modular architecture supports a wide range of deployment options, so you can select the best networking approach for your specific environment and needs. This includes the ability to run with a variety of CNI plugins and also leverage Calico’s IPAM capabilities and underlying network types, in non-overlay or overlay modes, with or without BGP.

Calico’s flexible modular architecture for networking includes the following:

  • Calico CNI network plugin – Connects pods to the host network namespace’s L3 routing using a pair of virtual ethernet devices (veth pair).
  • Calico CNI IPAM plugin – Allocates IP addresses for pods out of one or more configurable IP address ranges, dynamically allocating small blocks of IPs per node as required.
  • Overlay network modes – Calico provides both VXLAN or IP-in-IP overlay networks, including cross-subnet only modes.
  • Non-overlay network modes – Calico can provide non-overlay networks running on top of any underlying L2 network, or an L3 network that is either a public cloud network with appropriate cloud provider integration, or a BGP capable network (typically an on-prem network with standard Top-of-Rack routers).
  • Network policy enforcement – Calico’s networking and security policy enforcement engine implements the full range of Kubernetes Network Policy features, plus the extended features of Calico’s Networking and Security Policy.

In addition to providing both network and IPAM plugins, Calico also integrates with a number of other third-party CNI plugins and cloud provider integrations, including Amazon VPC CNI, Azure CNI, Azure cloud provider, Google cloud provider, host local IPAM, and Flannel.

Next steps:

Join our mailing list​

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