【K8S】Kubernetes中暴露外部IP地址来访问集群中的应用

本文是Kubernetes.io官方文档中介绍如何创建暴露外部IP地址的Kubernetes Service 对象。

学习目标

  • 运行Hello World应用程序的五个实例。
  • 创建一个暴露外部IP地址的Service对象。
  • 使用Service对象访问正在运行的应用程序。

准备工作

  • 安装kubectl
  • 使用Google提供商(如Google Container Engine或Amazon Web Services)创建Kubernetes群集。本教程创建一个 外部负载均衡器,它需要一个云提供商。
  • 配置kubectl与Kubernetes API服务器通信。有关说明,请参阅云提供商的文档。

在五个pod中运行的应用程序创建一个Service

1、在群集中运行Hello World应用程序:

kubectl run hello-world --replicas=5 --labels="run=load-balancer-example" --image=gcr.io/google-samples/node-hello:1.0  --port=8080

以上命令创建一个 Deployment 对象和一个关联的 ReplicaSet 对象。ReplicaSet 有五个 Pods,每个Pods都运行Hello World应用程序。

2、显示有关Deployment的信息:

kubectl get deployments hello-world
kubectl describe deployments hello-world

3、显示有关ReplicaSet对象的信息:

kubectl get replicasets
kubectl describe replicasets

4、使用deployment创建暴露的Service对象

kubectl expose deployment hello-world --type=LoadBalancer --name=my-service

5、显示有关Service的信息:

kubectl get services my-service

输出:

NAME         CLUSTER-IP     EXTERNAL-IP      PORT(S)    AGE
my-service   10.3.245.137   104.198.205.71   8080/TCP   54s

注意:如果外部IP地址显示为 ,请等待一分钟再次输入相同的命令。

6、显示Service有关详细信息:

kubectl describe services my-service

输出:

Name:           my-service
Namespace:      default
Labels:         run=load-balancer-example
Selector:       run=load-balancer-example
Type:           LoadBalancer
IP:             10.3.245.137
LoadBalancer Ingress:   104.198.205.71
Port:           <unset> 8080/TCP
NodePort:       <unset> 32377/TCP
Endpoints:      10.0.0.6:8080,10.0.1.6:8080,10.0.1.7:8080 + 2 more...
Session Affinity:   None
Events:

记录Service公开的外部IP地址。在此例子中,外部IP地址为104.198.205.71。还要注意Port的值。在这个例子中,端口是8080。

7、在上面的输出中,您可以看到该服务有多个端点:10.0.0.6:8080,10.0.1.6:8080,10.0.1.7:8080 + 2 more…。这些是运行Hello World应用程序的pod的内部地址。要验证这些是pod地址,请输入以下命令:

kubectl get pods --output=wide

输出类似于:

NAME                         ...  IP         NODE
hello-world-2895499144-1jaz9 ...  10.0.1.6   gke-cluster-1-default-pool-e0b8d269-1afc
hello-world-2895499144-2e5uh ...  0.0.1.8    gke-cluster-1-default-pool-e0b8d269-1afc
hello-world-2895499144-9m4h1 ...  10.0.0.6   gke-cluster-1-default-pool-e0b8d269-5v7a
hello-world-2895499144-o4z13 ...  10.0.1.7   gke-cluster-1-default-pool-e0b8d269-1afc
hello-world-2895499144-segjf ...  10.0.2.5   gke-cluster-1-default-pool-e0b8d269-cpuc

8、使用外部IP地址访问Hello World应用程序:

curl http://<external-ip>:<port>

是你Service的外部IP地址,并且 是Port你的Service描述中的值。

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

Hello Kubernetes!

删除方法

要删除服务,请输入以下命令:

kubectl delete services my-service

要删除Deployment,ReplicaSet和运行Hello World应用程序的Pods,请输入以下命令:

kubectl delete deployment hello-world

本文转自中文社区-Kubernetes中暴露外部IP地址来访问集群中的应用

猜你喜欢

转载自www.cnblogs.com/binghe001/p/13166705.html