从另一个 GKE 私有集群访问私有 GKE 集群中的节点端口服务

Access a Node Port Service in a private GKE Cluster from another GKE private cluster

我正在使用 Google 云并且我有两个 GKE 私有集群。

其中一个包含一些安装为 nodePort 的服务。另一个集群需要连接到这个集群并访问公开的服务。

暴露服务的集群只有一个节点有私有IP。我可以使用这个私有 IP 从另一个集群成功地 ping 这个节点。

但是我怎样才能访问这些服务呢?

我也尝试配置一些防火墙规则,但没有成功。

请查看下面的示例,其中显示了如何在两个私有 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

应用它并检查生成此 pods 的节点的 内部 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-europepod 地址范围
      • 转到Kubernetes Engine
      • 找到你的gke-private-cluster-europe
      • 点击查看详情
      • 复制 pod 地址范围,应该类似于:10.24.0.0/14

复制网络标签和 pod 范围后,您可以创建防火墙规则。请前往:

VPC Network -> Firewall rules -> Create a firewall rule

请具体查看使用网络标签和 pod 范围 ip 的部分,因为它对您来说会有所不同。

应用它并再次检查 gke-private-cluster-europe 中的 pod 是否可以访问 10.156.0.2:30051

它应该给你下面的输出:

Hello, world!
Version: 1.0.0
Hostname: hello-5d79ccdb55-6s8xh

如果您对此有任何疑问,请告诉我。