Kubernetes NetworkPolicies Blocking DNS

Mik*_*980 4 dns kubernetes kubernetes-networkpolicy azure-aks

I have an AKS cluster (Azure CNI) which I'm trying to implement NetworkPolicies on. I've created the network policy which is

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: myserver
spec:
  podSelector:
    matchLabels:
      service: my-server
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          service: myotherserver
    - podSelector:
        matchLabels:
          service: gateway
    - podSelector:
        matchLabels:
          service: yetanotherserver
    ports:
     - port: 8080
       protocol: TCP
  egress:
    - to:
      ports:
       - port: 53
         protocol: UDP
       - port: 53
         protocol: TCP
       - port: 5432
         protocol: TCP
       - port: 8080
         protocol: TCP
Run Code Online (Sandbox Code Playgroud)

but when I apply the policy I'm seeing recurring messages that the host name cannot be resolved. I've installed dnsutils on the myserver pod; and can see the DNS requests are timing out; and I've also tried installing tcpdump on the same pod; and I can see requests going from myserver to kube-dns. I'm not seeing any responses coming back.

If I delete the networkpolicy DNS comes straight back; so I'm certain there's an issue with my networkpolicy but can't find a way to allow the DNS traffic. If anyone can shed any light on where I'm going wrong it would be greatly appreciated!

Mag*_*nus 8

不需要name目标名称空间标签的解决方案。有必要定义 anamespaceSelector和 a podSelector。默认情况下namespaceSelector将定位 pod 自己的命名空间。

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-dns-access
  namespace: <your-namespacename>
spec:
  podSelector:
    matchLabels: {}
  policyTypes:
  - Egress
  egress:
  - to:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: kube-system
      podSelector:
        matchLabels:
          k8s-app: kube-dns
    ports:
    - protocol: UDP
      port: 53
Run Code Online (Sandbox Code Playgroud)

编辑:将命名空间选择器更改为仅kube-system基于kubernetes.io/metadata.name标签的目标命名空间。这假设您启用了自动标签。https://kubernetes.io/docs/concepts/overview/_print/#automatic-labelling

如果您没有启用此功能,那么最好的办法就是定义一个允许全部namespaceSelector以及podSelector.


Arg*_*dhu 6

为了避免重复,请创建单独的网络策略来开放 DNS 流量。首先我们标记kube-system命名空间。然后允许从所有 pod 到kube-system命名空间的 DNS 流量。

kubectl label namespace kube-system name=kube-system

kubectl create -f - <<EOF
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-dns-access
  namespace: <your-namespacename>
spec:
  podSelector:
    matchLabels: {}
  policyTypes:
  - Egress
  egress:
  - to:
    - namespaceSelector:
        matchLabels:
          name: kube-system
    ports:
    - protocol: UDP
      port: 53

EOF
Run Code Online (Sandbox Code Playgroud)