Clarification on Egress Traffic and NetworkPolicy YAML for Outgoing Traffic in Kubernetes

Hi everyone,

I’m working on creating a NetworkPolicy in Kubernetes for namespace ns1 with the following requirements:

Allow all pods in ns1 to only have outgoing traffic to pods in ns2.
Incoming traffic should not be affected.
The NetworkPolicy should still allow outgoing DNS traffic on port 53 (both TCP and UDP).

Here is the YAML for the NetworkPolicy I’m using:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: np
  namespace: ns1
spec:
  egress:
    - ports:
        - port: 53
          protocol: TCP
        - port: 53
          protocol: UDP
      to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: ns2
  podSelector: {}
  policyTypes:
    - Egress

Is the issue with the egress traffic due to the combination of namespaceSelector and ports under the same rule?
Should the ports be defined in a separate rule rather than within the same egress rule as shown in the YAML above?
I’d appreciate any guidance or suggestions on how to properly structure the NetworkPolicy to achieve the desired behavior.

There is a slight error in this.

What you have defined is a policy that says

allows all pods in namespace ns1 to connect to all pods in namespaces with labels kubernetes.io/metadata.name: ns2 on ports TCP 53 and UDP 53

Which basically means that pods in ns1 can make DNS requests to any pod in ns2

What is actually required is

allows all pods in namespace ns1 to connect to all namespaces, pods and IP addresses on ports TCP 53 and UDP 53

allows all pods in namespace ns1 to connect to all pods in namespaces with labels kubernetes.io/metadata.name: ns2 on all ports

which is

    - ports:
        - port: 53
          protocol: TCP
        - port: 53
          protocol: UDP
    - to:                            #<- Note the addition of "-" before to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: ns2

because the “ports” with no namespace or pod selector constraints is a separate rule to the namespace one.

1 Like

You can use this tool (not in the exam though) to get your policies explained.

1 Like