Kubernetes中暴露外部IP地址來訪問叢集中的應用_Kubernetes中文社群
阿新 • • 發佈:2018-12-27
本文是Kubernetes.io官方文件中介紹如何建立暴露外部IP地址的Kubernetes Service 物件。
學習目標
- 執行Hello World應用程式的五個例項。
- 建立一個暴露外部IP地址的Service物件。
- 使用Service物件訪問正在執行的應用程式。
準備工作
- 使用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地址顯示為<pending>,請等待一分鐘再次輸入相同的命令。
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>
<external-ip>是你Service的外部IP地址,並且<port>是Port你的Service描述中的值。
對成功請求的響應是一個hello訊息:
Hello Kubernetes!
刪除方法
要刪除服務,請輸入以下命令:
kubectl delete services my-service
要刪除Deployment,ReplicaSet和執行Hello World應用程式的Pods,請輸入以下命令:
kubectl delete deployment hello-world