原文地址:https://kubernetes.io/zh/docs/tutorials/stateless-application/expose-external-ip-address/
此頁面顯示如何創建公開外部 IP 地址的 Kubernetes 服務對象。
教程目標
- 運行 Hello World 應用程序的五個實例。
- 創建一個公開外部 IP 地址的 Service 對象。
- 使用 Service 對象訪問正在運行的應用程序。
準備開始
-
安裝 kubectl.
-
使用 Google Kubernetes Engine 或 Amazon Web Services 等雲供應商創建 Kubernetes 羣集。 本教程創建了一個外部負載均衡器,需要雲供應商。
-
配置
kubectl
與 Kubernetes API 服務器通信。有關說明,請參閱雲供應商文檔。
爲一個在五個 pod 中運行的應用程序創建服務
-
在集羣中運行 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 有五個 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=LoadBalancer --name=my-service
-
顯示有關 Service 的信息:
kubectl get services my-service
輸出類似於:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
my-service ClusterIP 10.3.245.137 104.198.205.71 8080/TCP 54s
注意:如果外部 IP 地址顯示爲 <pending>,請等待一分鐘再次輸入相同的命令。
-
顯示有關 Service 的詳細信息:
kubectl describe services my-service
輸出類似於:
Name: my-service
Namespace: default
Labels: run=load-balancer-example
Annotations: <none>
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: <none>
記下服務公開的外部 IP 地址(LoadBalancer Ingress
)。 在本例中,外部 IP 地址是 104.198.205.71。還要注意 Port
和 NodePort
的值。 在本例中,Port
是 8080,NodePort
是32377。
-
在前面的輸出中,您可以看到服務有幾個端點: 10.0.0.6:8080、10.0.1.6:8080、10.0.1.7:8080 和另外兩個, 這些都是正在運行 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 ... 10.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
-
使用外部 IP 地址(
LoadBalancer Ingress
)訪問 Hello World 應用程序:curl http://<external-ip>:<port>
其中 <external-ip>
是您的服務的外部 IP 地址(LoadBalancer Ingress
), <port>
是您的服務描述中的 port
的值。 如果您正在使用 minikube,輸入 minikube service my-service
將在瀏覽器中自動打開 Hello World 應用程序。
成功請求的響應是一條問候消息:
Hello Kubernetes!
清理現場
要刪除服務,請輸入以下命令:
kubectl delete services my-service
要刪除正在運行 Hello World 應用程序的 Deployment,ReplicaSet 和 Pod,請輸入以下命令:
kubectl delete deployment hello-world