我在Google Kubernetes Engine(GKE)上运行了Kubernetes集群,并启用了网络策略支持 . 我为它创建了一个nginx部署和负载均衡器:
kubectl run nginx --image=nginx
kubectl expose deployment nginx --port=80 --type=LoadBalancer
然后我创建了这个网络策略,以确保群集中的其他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
现在,我的群集中的其他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
然而,令我惊讶的是,使用我的外部浏览器我也无法通过负载均衡器连接到它:
open http://$(kubectl get svc nginx --output=jsonpath={.status.loadBalancer.ingress[0].ip})
如果我删除该策略,它将再次开始工作 .
所以,我的问题是:如何阻止其他pod到达nginx,但是通过负载均衡器保持访问权限?
1 回答
我在网络策略食谱库中讨论了这个问题:https://github.com/ahmetb/kubernetes-networkpolicy-tutorial/blob/a18f9e6e/08-allow-external-traffic.md
“在DENYING本地流量时允许EXTERNAL负载均衡器”不是一个有意义的用例,因此无法使用网络策略 .
要使
Service
type = LoadBalancer和Ingress
资源起作用,您必须允许所有流量通过这些资源选择的容器 .如果你真的想要你可以使用
from.ipBlock.cidr
和from.ipBlock.cidr.except
资源来允许来自0.0.0.0/0
(所有IPv4)的流量,然后排除10.0.0.0/8
(或GKE使用的任何私有IP范围) .