Kubernetes NetworkPolicy允许负载均衡器

Chr*_*aan 5 kubernetes google-kubernetes-engine

我有一个在启用了网络策略支持的Google Kubernetes Engine(GKE)上运行的Kubernetes集群。我为此创建了一个nginx部署和负载均衡器:

kubectl run nginx --image=nginx
kubectl expose deployment nginx --port=80 --type=LoadBalancer
Run Code Online (Sandbox Code Playgroud)

然后,我创建了此网络策略,以确保集群中的其他Pod将不再能够连接到它:

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: access-nginx
spec:
  podSelector:
    matchLabels:
      run: nginx
  ingress:
  - from:
      - namespaceSelector:
          matchLabels:
            name: kube-system
    ports:
    - protocol: TCP
      port: 80
Run Code Online (Sandbox Code Playgroud)

现在,群集中的其他Pod无法到达(如预期的那样):

kubectl run busybox --rm -ti --image=busybox /bin/sh
If you don't see a command prompt, try pressing enter.
/ # wget --spider --timeout=1 nginx
Connecting to nginx (10.63.254.50:80)
wget: download timed out
Run Code Online (Sandbox Code Playgroud)

但是,令我惊讶的是,使用我的外部浏览器,我也无法再通过负载平衡器连接到它:

open http://$(kubectl get svc nginx --output=jsonpath={.status.loadBalancer.ingress[0].ip})
Run Code Online (Sandbox Code Playgroud)

如果我删除该策略,它将再次开始工作。

所以,我的问题是:如何阻止其他Pod到达Nginx,但保持通过负载均衡器的访问权限打开?

Ahm*_*gle 9

我在我的网络策略食谱存储库中讨论过这一点。

允许外部负载均衡器同时拒绝本地流量”不是一个有意义的用例,因此不可能使用网络策略。

为了使Servicetype=LoadBalancer 和Ingress资源正常工作,您必须允许所有流量流向这些资源选择的 Pod。

如果您确实想要,可以使用from.ipBlock.cidrfrom.ipBlock.cidr.except资源来允许来自0.0.0.0/0(所有 IPv4)的流量,然后排除10.0.0.0/8(或 GKE 使用的任何私有 IP 范围)。


小智 8

我最近不得不做类似的事情。我需要一个策略,不允许来自其他命名空间的 pod 与 prod 通信,但允许LoadBalancer 服务访问 prod 中的 pod。这是有效的(基于艾哈迈德的帖子):

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: isolate-prod
  namespace: prod
spec:
  podSelector: {}
  ingress:
  - from:
    - podSelector: {}
  - from:
    - ipBlock:
        cidr: '0.0.0.0/0'
        except: ['10.0.0.0/8']
Run Code Online (Sandbox Code Playgroud)