Home > Back-end >  K8s NetworkPolicy behavior when `ports: {}`
K8s NetworkPolicy behavior when `ports: {}`

Time:01-04

The K8s documentation on NetworkPolicy states that if the spec.ingress.from.ports array is not specified, traffic is allowed from any port for the matching peers array:

List of ports which should be made accessible on the pods selected for this rule. Each item in this list is combined using a logical OR. If this field is empty or missing, this rule matches all ports (traffic not restricted by port). If this field is present and contains at least one item, then this rule allows traffic only if the traffic matches at least one port in the list.

But what if one of the port items inside of ports is created like this?

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: empty-port-item-network-policy
  namespace: some-namespace
spec:
  podSelector:
    matchLabels:
      app: front
  ingress:
    - from:
      - podSelector: {}

      ports:
        - {}

When I describe this NetworkPolicy, I don't get enough information (ignore PodSelector=none):

Created on:   2023-01-02 18:58:32  0200 IST
Labels:       <none>
Annotations:  <none>
Spec:
  PodSelector:     app=front
  Allowing ingress traffic:
    To Port: <nil>/TCP
    From:
      PodSelector: <none>
  Not affecting egress traffic
  Policy Types: Ingress

What does To Port: <nil>/TCP mean here? Any port? all ports?

CodePudding user response:

You are passing an empty array to the ports when using:

  ports:
    - {}

This means that no ports are allowed. Everything is blocked.

When omitting the ports entry, you would allow traffic to all ports. kubectl describe output:

  Allowing ingress traffic:
    To Port: <any> (traffic allowed to all ports)

The yaml would be something like this:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: empty-port-item-network-policy
  namespace: some-namespace
spec:
  podSelector:
    matchLabels:
      app: front
  ingress:
    - from:
      - podSelector: {}
  • Related