Network policies on Kubernetes

2 min read | by Jordi Prats

Network policies are objects that allows you to control the flow of connections to and from pods. By default all pods are completely open to all communications, but as soon as a pod is selected by a policy, it is no longer be considered open: just the connections allowed by the NetworkPolicy will be allowed

We can configure both directions:

  • Ingress: traffic comming into the pod
  • Egress: traffic leaving the pod to another destination

The from and to selectors are used to allow ingress an egress traffic

Just as in the deployments, we can use labels to determine which Pods or namespaces the NetworkPolicy applies:

  • podSelector
  • namespaceSelector

But we can also use IP ranges using:

  • ipBlock: CIDR notation

As a simple example, the following NetworkPolicy is applied to all the Pods that have the label role=test. Allowing traffic from any to port 8080. Meanwhile, only the UDP/53, TCP/53, TCP/80 and TCP/443 is allowed for traffic originated on the Pod:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: demo-network-policy
spec:
  podSelector:
    matchLabels:
      role: test
  ingress:
  - ports:
    - protocol: TCP
      port: 8080
  egress:
  - to:
    - ipBlock:
        cidr: 0.0.0.0/0
    ports:
    - protocol: TCP 
      port: 53
    - protocol: UDP 
      port: 53
    - protocol: TCP 
      port: 80
    - protocol: TCP 
      port: 443

But we can combine different types of origins on the same NetworkPolicy. For example, the following one allows a specific network range (with an exception), a specific namespace and a set of Pods that matches a the label role=frontend:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: test-network-policy
  namespace: default
spec:
  podSelector:
    matchLabels:
      role: db
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - ipBlock:
        cidr: 172.17.0.0/16
        except:
        - 172.17.1.0/24
    - namespaceSelector:
        matchLabels:
          project: myproject
    - podSelector:
        matchLabels:
          role: frontend
    ports:
    - protocol: TCP
      port: 8888

Posted on 20/12/2021