免责声明:我无权访问 DigitalOcean。我已经在 GCP 上使用我的 k8s 1.18.2 集群对此进行了分析和测试。确保您也可以满足DigitalOcean的先决条件:
网络策略由网络插件实现。要使用网络策略,您必须使用支持 NetworkPolicy 的网络解决方案。在没有实现它的控制器的情况下创建 NetworkPolicy 资源将无效
有一些资源可以帮助您实现目标。首先,查看本指南:允许来自外部客户端的流量:
此网络策略允许来自公共 Internet 的外部客户端直接或通过负载均衡器访问 pod。
为了工作,Service type=LoadBalancer
和Ingress
资源必须允许所有流量到这些资源选择的 Pod。
请参见下面的示例:
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: web-allow-external
spec:
podSelector:
matchLabels:
app: web
ingress:
- from: []
以下清单允许来自所有来源的流量(来自集群的内部和外部)。
我已经通过以下步骤重现了您的用例:
安装 Nginx Ingress 并用purpose=testing
.
创建并标记了以下命名空间:ingress-nginx
as purpose=testing
、monitoring
aspurpose=monitoring
和ci
as purpose=ci
。
在、和命名空间中应用 adeployment
和 a :service
default
ingress-nginx
monitoring
ci
apiVersion: apps/v1
kind: Deployment
metadata:
name: my1
namespace: <one_of_the_listed_above>
spec:
selector:
matchLabels:
run: my1
replicas: 2
template:
metadata:
labels:
run: my1
spec:
containers:
- name: my1
image: nginx
ports:
- containerPort: 80
apiVersion: v1
kind: Service
metadata:
name: my1
namespace: <one_of_the_listed_above>
labels:
run: my1
spec:
ports:
- port: 80
protocol: TCP
selector:
run: my1
- 创建了一个入口:
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: my1
namespace: ingress-nginx
annotations:
# If the class annotation is not specified it defaults to "gce".
kubernetes.io/ingress.class: "nginx"
spec:
rules:
- http:
paths:
- path: /
backend:
serviceName: my1
servicePort: 80
验证命名空间和负载均衡器之间的连接。
创建了以下内容NetworkPolicy
:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-monitoring-ci
namespace: ingress-nginx
spec:
podSelector: {}
ingress:
- from:
- namespaceSelector:
matchLabels:
purpose: ci
- from:
- namespaceSelector:
matchLabels:
purpose: monitoring
- from:
- namespaceSelector:
matchLabels:
purpose: testing
通过上面的配置,命名空间中的 podingress-nginx
应该能够接收来自命名空间的流量。此外,它们将在内部接收标记为 的命名空间内的流量。monitoring
ci
ingress-nginx
testing
还要检查负载均衡器服务中的externalTrafficPolicy是否设置为Local
或Cluster
。如果将其设置为Cluster
Ingress,则将具有运行 Ingress pod 的节点的 IP。如果发生这种情况,您还需要创建以下配置:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-nginx-controller
namespace: ingress-nginx
spec:
podSelector:
matchLabels:
app.kubernetes.io/instance: ingress-nginx
ingress:
- from:
- ipBlock:
cidr: 0.0.0.0/0
except:
- 10.16.0.0/14 #pod ip range
使用cidr: 0.0.0.0/0
将允许所有传入流量并添加except:
将允许您根据 DigitalOcean 配置(我无权访问)调整您的需求。
另请注意,从 k8s v1.19 开始,apiVersion: networking.k8s.io/v1beta1
for Ingress 被替换为v1
. 确保您使用的是正确的版本控制。
最后要记住的是,您还应该将这些策略用于出口,而不仅仅是入口。在阻止出口时,您可能会遇到 DNS 解析问题,这需要您添加规则才能使 pod 能够向 DNS 发送请求。更多细节在这里。