Skip to content

Organizations that are looking to control traffic at the network or transport layer can use a NetworkPolicy. A NetworkPolicy is a Kubernetes resource that defines how a pod is allowed to communicate to other network entities. The entities that a pod can communicate with are other pods, other namespaces, and IP blocks. When using a pod or namespace based policy you use a selector(podSelector, namespaceSelector) to define which traffic is allowed to/from the pods matching the selector. Network policies that are IP based are defined using CIDR ranges.

In a newly provisioned cluster all pods are allowed to communicate with one another. Kubernetes does not initialize the cluster with any network policies so it is up to the user to configure and apply the appropriate policies.

Network policies are implemented using Network Plugins. Network plugins come in two forms, the first being a CNI plugin which adheres to the Container Network Interface (CNI) specification. The second is a basic plugin called Kubenet. Managed clusters use Calico as it provides full support for all Kubernetes network policy features.


Sample Network Policies

Namespace Isolation

This sample policy when applied to a namespace will deny all traffic to or from pods to pods outside the namespace. Intra-namespace communication is allowed.

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: network-policy-namespace-a
spec:
  podSelector:
    matchLabels: {}

Inter-Namespace Communication

This sample policy when applied to a namespace will allow all traffic from a namespace with the label ns-policy=namespace-b. The label will need to be applied to the appropriate namespace. Communication to other namespaces will be denied.

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: np-allow-ns-a
spec:
  podSelector:
    matchLabels: {}
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          ns-policy: namespace-b
  egress:
  - to:
    - namespaceSelector:
        matchLabels:
          ns-policy: namespace-b  

Labels will need to be applied to namespace-b. This sample manifest will set the labels of namespace-b to the namespaceSelector defined in the NetworkPolicy above.

kind: Namespace
apiVersion: v1
metadata:
  name: namespace-b
  labels:
    ns-policy: namespace-b