网络策略不允许名称空间内的通信

时间:2020-07-09 18:31:27

标签: kubernetes kubernetes-networkpolicy

我在设置对我来说不错的网络策略时遇到了麻烦。这是同一个命名空间中的两个Pod

k get po --show-labels
NAME                         READY   STATUS    RESTARTS   AGE   LABELS
nfs-server-ccb8d5ff6-7rtr4   1/1     Running   0          22h   role=nfs-server
nginx-jpm-549b69bf68-x5hd7   1/1     Running   0          21h   app=nginx-jpm

并且我使用以下网络策略规范将流量限制为nfs-server pod:

spec:
  podSelector:
    matchLabels:
      role: nfs-server
  policyTypes:
  - Ingress
  - Egress
  ingress:
  # Allow inbound from nginx-jpm on all ports
  - from:
    - podSelector:
        matchLabels:
          app: nginx-jpm
  egress:
  # Allow outbound DNS traffic inside the cluster (kube-system namespace is not labelled)
  - to:
    - namespaceSelector: {}
    ports:
    - protocol: "UDP"
      port: 53

我执行了Nginx Pod,无法连接到NFS服务器Pod

root@nginx-jpm-549b69bf68-x5hd7:/# telnet nfs-server.jenkinsrepo.svc.cluster.local 111
Trying 172.22.117.55...
If I delete the network policy, it works then
root@nginx-jpm-549b69bf68-x5hd7:/# telnet nfs-server.jenkinsrepo.svc.cluster.local 111
Trying 172.22.117.55...
Connected to nfs-server.jenkinsrepo.svc.cluster.local.
Escape character is '^]'.

我的网络政策中是否缺少某些内容?命名空间中没有其他网络策略。

2 个答案:

答案 0 :(得分:1)

由于您拥有podSelector来选择带有role: nfs-server标签的Pod,所以出口规则仅适用于那些Pod,因此出口被Nginx Pod阻止了。您可能应该为出口到集群DNS创建单独的网络策略,该集群适用于所有Pod。

答案 1 :(得分:0)

您的出口规则被转换为将这些规则应用于名称空间未标记为“ AND”端口53 UDP(规则的“ AND”)的规则流量。即使DNS出口流量可能正在工作,来自所有pod的所有其他出口流量仍被阻止,这可能是原因。

如果您尝试以下操作,则在以下情况下将允许传出流量:(目标Pod具有未标记的名称空间)或((端口为53 UDP)或(端口为53 TCP))

egress:
   - to:
     - namespaceSelector: {}
   - ports:                  # 2nd egress rule
     - port: 53                # allow DNS UDP
       protocol: UDP
     - port: 53                # allow DNS TCP
       protocol: TCP

    

链接:https://docs.projectcalico.org/security/tutorials/kubernetes-policy-advanced