使用服务访问集群中的应用程序
本页面展示了如何创建一个 Kubernetes Service 对象,外部客户端可以使用该对象访问在集群中运行的应用程序。该 Service 为具有两个运行实例的应用程序提供负载均衡。
准备工作
你需要拥有一个 Kubernetes 集群,并且 kubectl 命令行工具已配置为与你的集群通信。建议在至少有两个不充当控制平面主机的节点组成的集群上运行本教程。如果你尚未拥有集群,可以使用 minikube 创建一个,或者使用这些 Kubernetes 游乐场之一
目标
- 运行 Hello World 应用程序的两个实例。
- 创建一个公开节点端口的 Service 对象。
- 使用 Service 对象访问正在运行的应用程序。
为运行在两个 Pod 中的应用程序创建 Service
以下是应用程序 Deployment 的配置文件
apiVersion: apps/v1
kind: Deployment
metadata:
name: hello-world
spec:
selector:
matchLabels:
run: load-balancer-example
replicas: 2
template:
metadata:
labels:
run: load-balancer-example
spec:
containers:
- name: hello-world
image: us-docker.pkg.dev/google-samples/containers/gke/hello-app:2.0
ports:
- containerPort: 8080
protocol: TCP
在集群中运行一个 Hello World 应用程序:使用上述文件创建应用程序 Deployment
kubectl apply -f https://k8s.io/examples/service/access/hello-application.yaml
上述命令会创建一个 Deployment 和一个关联的 ReplicaSet。该 ReplicaSet 有两个 Pod,每个 Pod 都运行 Hello World 应用程序。
显示有关 Deployment 的信息
kubectl get deployments hello-world kubectl describe deployments hello-world
显示有关 ReplicaSet 对象的信息
kubectl get replicasets kubectl describe replicasets
创建一个公开 Deployment 的 Service 对象
kubectl expose deployment hello-world --type=NodePort --name=example-service
显示有关 Service 的信息
kubectl describe services example-service
输出类似于:
Name: example-service Namespace: default Labels: run=load-balancer-example Annotations: <none> Selector: run=load-balancer-example Type: NodePort IP: 10.32.0.16 Port: <unset> 8080/TCP TargetPort: 8080/TCP NodePort: <unset> 31496/TCP Endpoints: 10.200.1.4:8080,10.200.2.5:8080 Session Affinity: None Events: <none>
记下 Service 的 NodePort 值。例如,在上述输出中,NodePort 值为 31496。
列出正在运行 Hello World 应用程序的 Pod
kubectl get pods --selector="run=load-balancer-example" --output=wide
输出类似于:
NAME READY STATUS ... IP NODE hello-world-2895499144-bsbk5 1/1 Running ... 10.200.1.4 worker1 hello-world-2895499144-m1pwt 1/1 Running ... 10.200.2.5 worker2
获取运行 Hello World Pod 的其中一个节点的公共 IP 地址。如何获取此地址取决于你设置集群的方式。例如,如果你使用 Minikube,可以通过运行
kubectl cluster-info
查看节点地址。如果你使用 Google Compute Engine 实例,可以使用gcloud compute instances list
命令查看节点的公共地址。在你选择的节点上,创建一条防火墙规则,允许 TCP 流量通过你的节点端口。例如,如果你的 Service 的 NodePort 值为 31568,则创建一条防火墙规则,允许 TCP 流量通过端口 31568。不同的云提供商提供不同的配置防火墙规则的方式。
使用节点地址和节点端口访问 Hello World 应用程序
curl http://<public-node-ip>:<node-port>
其中
<public-node-ip>
是你节点的公共 IP 地址,<node-port>
是你 Service 的 NodePort 值。成功请求的响应是 hello 消息Hello, world! Version: 2.0.0 Hostname: hello-world-cdd4458f4-m47c8
使用 Service 配置文件
作为使用 kubectl expose
的替代方案,你可以使用 Service 配置文件 来创建 Service。
清理
要删除 Service,输入以下命令
kubectl delete services example-service
要删除 Deployment、ReplicaSet 以及运行 Hello World 应用程序的 Pod,请输入此命令
kubectl delete deployment hello-world
下一步
遵循 使用 Service 连接应用程序 教程。