Kubernetes NetworkPolicy允许负载均衡器 [英] Kubernetes NetworkPolicy allow loadbalancer
问题描述
我有一个在Google Kubernetes Engine(GKE)上运行的Kubernetes集群,并且启用了网络策略支持. 我为此创建了一个nginx部署和负载均衡器:
I have a Kubernetes cluster running on Google Kubernetes Engine (GKE) with network policy support enabled. I created an nginx deployment and load balancer for it:
kubectl run nginx --image=nginx
kubectl expose deployment nginx --port=80 --type=LoadBalancer
然后,我创建了此网络策略,以确保集群中的其他Pod不再能够连接到它:
Then I created this network policy to make sure other pods in the cluster won't be able to connect to it anymore:
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
现在群集中的其他Pod无法到达(如预期的那样):
Now other pods in my cluster can't reach it (as intended):
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
但是,令我惊讶的是,使用外部浏览器,我也无法再通过负载平衡器连接到它:
However, it surprised me that using my external browser I also can't connect anymore to it through the load balancer:
open http://$(kubectl get svc nginx --output=jsonpath={.status.loadBalancer.ingress[0].ip})
如果我删除该政策,它将再次开始起作用.
If I delete the policy it starts to work again.
所以,我的问题是:如何阻止其他Pod到达Nginx,但保持通过负载均衡器的访问权限打开?
So, my question is: how do I block other pods from reaching nginx, but keep access through the load balancer open?
推荐答案
I talked about this in my Network Policy recipes repository: https://github.com/ahmetb/kubernetes-networkpolicy-tutorial/blob/a18f9e6e/08-allow-external-traffic.md
"在拒绝本地流量时允许外部负载平衡器"不是一个有意义的用例,因此无法使用网络策略.
"Allowing EXTERNAL load balancers while DENYING local traffic" is not a use case that makes sense, therefore it's not possible to using network policy.
要使Service
type = LoadBalancer和Ingress
资源正常工作,必须允许所有流量流向这些资源选择的容器.
For Service
type=LoadBalancer and Ingress
resources to work, you must allow ALL traffic to the pods selected by these resources.
如果您真的想要使用from.ipBlock.cidr
和from.ipBlock.cidr.except
资源,以允许来自0.0.0.0/0
(所有IPv4)的流量,然后排除10.0.0.0/8
(或GKE使用的任何私有IP范围).
If you REALLY want you can use the from.ipBlock.cidr
and from.ipBlock.cidr.except
resources to allow traffic from 0.0.0.0/0
(all IPv4) and then excluding 10.0.0.0/8
(or whatever private IP range GKE uses).
这篇关于Kubernetes NetworkPolicy允许负载均衡器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!