正如您在 cmets 中提到的,您正在使用 Kind 工具来运行 Kubernetes。代替不支持Kubernetes network policies 的kindnet CNI plugin(Kind 的默认CNI 插件),您可以使用支持Kubernetes 网络策略的Calico CNI plugin + 它有自己的类似解决方案,称为Calico network policies。
示例 - 我将使用禁用的默认类型 CNI 插件 + enabled NodePort 创建集群进行测试(假设您已经安装了 kind + kubectl 工具):
kind-cluster-config.yaml 文件:
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
networking:
disableDefaultCNI: true # disable kindnet
podSubnet: 192.168.0.0/16 # set to Calico's default subnet
nodes:
- role: control-plane
extraPortMappings:
- containerPort: 30000
hostPort: 30000
listenAddress: "0.0.0.0" # Optional, defaults to "0.0.0.0"
protocol: tcp # Optional, defaults to tcp
使用上述配置创建集群的时间:
kind create cluster --config kind-cluster-config.yaml
集群准备好后,我将安装 Calico CNI 插件:
kubectl apply -f https://docs.projectcalico.org/manifests/calico.yaml
我会等到所有 calico pod 都准备好(kubectl get pods -n kube-system 命令检查)。然后,我将创建示例nginx deployment + 服务类型 NodePort 用于访问:
nginx-deploy-service.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
selector:
matchLabels:
app: nginx
replicas: 2 # tells deployment to run 2 pods matching the template
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.14.2
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
type: NodePort
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
nodePort: 30000
让我们应用它:kubectl apply -f nginx-deploy-service.yaml
到目前为止一切顺利。现在我将尝试使用节点 IP 访问nginx-service(kubectl get nodes -o wide 命令检查节点 IP 地址):
curl 172.18.0.2:30000
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
...
好的,它正在工作。
现在是 install calicoctl 并应用一些示例策略 - based on this tutorial - 仅阻止标签为 app 且值为 nginx 的 pod 的入口流量:
calico-rule.yaml:
apiVersion: projectcalico.org/v3
kind: GlobalNetworkPolicy
metadata:
name: default-deny
spec:
selector: app == "nginx"
types:
- Ingress
应用它:
calicoctl apply -f calico-rule.yaml
Successfully applied 1 'GlobalNetworkPolicy' resource(s)
现在我无法访问以前工作的地址172.18.0.2:30000。该政策运行良好!
阅读有关印花布政策的更多信息:
另请查看this GitHub topic,了解有关 Kind 中 NetworkPolicy 支持的更多信息。
编辑:
看起来像 Calico 插件supports as well Kubernetes NetworkPolicy,所以你可以安装 Calico CNI 插件并应用以下策略:
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: default-deny
spec:
podSelector:
matchLabels:
app: nginx
policyTypes:
- Ingress
我测试了它,它似乎也可以正常工作。