请看下面的示例,该示例显示了如何在两个私有 GKE 集群之间建立与服务 (NodePort) 的连接:
本示例将使用两个 GKE 集群:
-
gke-private-cluster-main - 这将是带有简单 hello-app 的集群
-
gke-private-cluster-europe - 此集群将能够与主集群通信
为简化起见,所有集群将只有一个节点。
在gke-private-cluster-main 上创建部署和服务
下面是一个简单的hello-app 示例和一个将在端口30051 上公开hello-app 的服务:
apiVersion: apps/v1
kind: Deployment
metadata:
name: hello
spec:
selector:
matchLabels:
app: hello
version: 1.0.0
replicas: 3
template:
metadata:
labels:
app: hello
version: 1.0.0
spec:
containers:
- name: hello
image: "gcr.io/google-samples/hello-app:1.0"
env:
- name: "PORT"
value: "50001"
---
apiVersion: v1
kind: Service
metadata:
name: hello-service
spec:
selector:
app: hello
ports:
- name: hello-port
port: 50001
targetPort: 50001
nodePort: 30051
type: NodePort
应用它并检查生成此 pod 的节点的 内部 IP 地址。您可以使用以下任一方法进行检查:
-
GCP -> Compute Engine -> VM Instances
kubectl get nodes -o wide
在我的例子中是10.156.0.2
尝试从gke-private-cluster-europe访问它
您可以通过 SSH 连接到 gke-private-cluster-europe 的节点并尝试从节点调用命令:
curl 10.156.0.2:30051。您应该能够与该服务进行通信并获得如下输出:
Hello, world!
Version: 1.0.0
Hostname: hello-5d79ccdb55-vrrbs
要从 pod 内部检查连接,您需要一个已经内置 curl 的图像。互联网是各种很棒的东西的地方,实际上有一个可用 curl 的图像。您可以使用以下 YAML 生成带有 curl 的 pod:
apiVersion: v1
kind: Pod
metadata:
name: curl
namespace: default
spec:
containers:
- image: curlimages/curl
command:
- sleep
- "infinity"
imagePullPolicy: IfNotPresent
name: curl
restartPolicy: Always
应用上面的YAML后,你可以exec进入pod并使用以下命令检查自己:
$ kubectl exec -it curl -- /bin/sh
$ curl 10.156.0.2:30051
集群内部的输出将如下所示:
curl: (28) Failed to connect to 10.156.0.2 port 30051: Operation timed out
它适用于节点,但不适用于 pod。
允许流量:
要允许上述网络连接,您需要:
- 打开
Google Cloud Platform
- 检查
gke-private-cluster-main 节点的网络标记
- 转到
Compute Engine
- 找到
gke-private-cluster-main的节点
- 点击获取更多详情
-
复制应该类似于:
gke-gke-private-cluster-main-80fe50b2-node 的网络标记
- 检查
gke-private-cluster-europe的pod地址范围:
- 转到
Kubernetes Engine
- 找到您的
gke-private-cluster-europe
- 点击获取更多详情
-
复制 pod 地址范围,应类似于:
10.24.0.0/14
复制网络标签和 pod 范围后,您可以创建防火墙规则。请前往:
VPC Network -> Firewall rules -> Create a firewall rule
请仔细查看使用网络标签和 pod range ip 的部分,因为它会因您而异。
应用它并再次检查 gke-private-cluster-europe 中的 pod 是否可以访问 10.156.0.2:30051。
它应该给你下面的输出:
Hello, world!
Version: 1.0.0
Hostname: hello-5d79ccdb55-6s8xh
如果您对此有任何疑问,请告诉我。