使用 service 访问群集中的应用程序

    • 运行 Hello World 应用程序的两个实例。
    • 创建一个暴露 node 节点端口的 Service 对象。
    • 使用 Service 对象访问正在运行的应用程序。
    1. 在集群中运行 Hello World 应用程序:

      上述命令创建一个 Deployment 对象和一个相关联的 对象。该 ReplicaSet 有两个 Pod,每个 Pod 中都运行一个 Hello World 应用程序。

    2. 显示关于该 Deployment 的信息:

      1. kubectl describe deployments hello-world
    3. 显示 ReplicaSet 的信息:

      1. kubectl get replicasets
    4. 创建一个暴露该 Deployment 的 Service 对象:

      1. kubectl expose deployment hello-world --type=NodePort --name=example-service
    5. 输出类似于:

      1. Name: example-service
      2. Namespace: default
      3. Labels: run=load-balancer-example
      4. Selector: run=load-balancer-example
      5. IP: 10.32.0.16
      6. Port: <unset> 8080/TCP
      7. NodePort: <unset> 31496/TCP
      8. Endpoints: 10.200.1.4:8080,10.200.2.5:8080
      9. No events.

      记下服务的 NodePort 值。例如,在前面的输出中,NodePort 值为 31496。

    6. 列出运行 Hello World 应用程序的 Pod:

      1. kubectl get pods --selector="run=load-balancer-example" --output=wide

      输出类似于:

      1. NAME READY STATUS ... IP NODE
      2. hello-world-2895499144-m1pwt 1/1 Running ... 10.200.2.5 worker2
    7. 获取正在运行 Hello World 应用程序的 Pod 的其中一个节点的 public IP 地址。如何得到这个地址取决于您的集群设置。例如,如果您使用 Minikube,可以通过运行 kubectl cluster-info 查看节点地址。如果您是使用 Google Compute Engine 实例,可以使用 gcloud compute instances list 命令查看您的公共地址节点。

    8. 使用节点地址和节点端口访问 Hello World 应用程序:

      其中 <public-node-ip> 是您节点的 public IP地址,而 <node-port> 是您服务的 NodePort 值。

      对成功请求的响应是一个 hello 消息:

      1. Hello Kubernetes!

    作为使用 kubectl expose 的替代方法,您可以使用 来创建 Service。

    要删除 Service,输入以下命令:

    1. kubectl delete services example-service

    了解更多关于 使用 service 连接应用程序