Kubernetes出口网络策略不适用于所选的Pod

时间:2020-07-25 12:56:48

标签: nginx kubernetes weave

在kube集群上设置出口网络策略时,我遇到了一个奇怪的问题。

基本上我希望我的Pod A仅访问Pod B。

我有两个豆荚:

  1. hello-k8s-deploy
  2. nginx

hello-k8s-deploy Pod通过NodePort在端口8080上公开API。 我的nginx pod只是访问API的图像。

因此,我们尝试登录nginx pod并访问hello-k8s-deploy pod公开的API。

enter image description here

上面显示API返回的消息以Hello K8s!

开头

现在让我们在我的nginx pod上应用网络策略,以便它只能访问此API,而不能访问其他任何

网络政策:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: test-network-policy
  namespace: app
spec:
  podSelector:
    matchLabels:
      run: nginx
  egress:
    - to:
      - podSelector:
          matchLabels:
            app: hello-k8s-deploy
  policyTypes:
   - Egress

上述策略将应用于标签为run: nginx的广告连播

规则是允许流量带有标签app: hello-k8s-deploy的pod

让我们通过查看两个Pod Nginx和hello-k8s-deploy的定义来验证它

nginx:

enter image description here

hello-k8s-deploy

enter image description here

我们可以看到两个标签都与网络策略匹配。

应用网络策略并再次访问nginx之后,我希望能同样工作并从API得到响应,但出现以下错误。

enter image description here

请注意:

  1. 所有资源都在同一个命名空间app
  2. 我的网络插件是weave-net,根据文档支持网络策略。
  3. 我什至尝试指定名称空间选择器并添加端口8080。

1 个答案:

答案 0 :(得分:1)

我终于解决了这个问题,基本上我遇到的问题是could not resolve host hello-k8s-svc。这意味着k8s尝试使用此主机进行连接,并通过dns名称(服务名称)进行解析。

并且由于我的Pod只允许出口到hello-k8s-deploy,所以它失败了,因为它还需要连接到kube-dns来解析dns。因此,在应用出口之前,请确保名称空间中的Pod或所有Pod都允许连接到kube-dns以进行dns解析。

此修复程序只是在所有Pod上创建一个出口资源,以便在特定于Pod的出口配置之上连接到kube-dns。

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all-egress
spec:
  podSelector: {}
  egress:
  - to:
    - namespaceSelector:
        matchLabels:
          networking/namespace: kube-system
      podSelector:
        matchLabels:
          k8s-app: kube-dns
    ports:
    - protocol: TCP
      port: 53
    - protocol: UDP
      port: 53
  policyTypes:
  - Egress

在我的情况下,我标记了kube-system命名空间:

 kubectl label namespace kube-system networking/namespace=kube-system