[英]Kubernetes to find Pod IP from another Pod
我有以下pods hello-abc
和hello-def
。
我想將數據從hello-abc
發送到hello-def
。
pod hello-abc
如何知道hello-def
的IP地址?
我想以編程方式執行此操作。
hello-abc
找到hello-def
的最簡單方法是什么?
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: hello-abc-deployment
spec:
replicas: 1
template:
metadata:
labels:
app: hello-abc
spec:
containers:
- name: hello-abc
image: hello-abc:v0.0.1
imagePullPolicy: Always
args: ["/hello-abc"]
ports:
- containerPort: 5000
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: hello-def-deployment
spec:
replicas: 1
template:
metadata:
labels:
app: hello-def
spec:
containers:
- name: hello-def
image: hello-def:v0.0.1
imagePullPolicy: Always
args: ["/hello-def"]
ports:
- containerPort: 5001
---
apiVersion: v1
kind: Service
metadata:
name: hello-abc-service
spec:
ports:
- port: 80
targetPort: 5000
protocol: TCP
selector:
app: hello-abc
type: NodePort
---
apiVersion: v1
kind: Service
metadata:
name: hello-def-service
spec:
ports:
- port: 80
targetPort: 5001
protocol: TCP
selector:
app: hello-def
type: NodePort
前言
由於您已定義了路由到每個部署的服務,因此如果您已將服務和部署部署到同一命名空間,則可以在許多現代kubernetes集群中利用kube-dns並簡單地按名稱引用服務。
不幸的是,如果您的群集中未配置kube-dns
(盡管不太可能),則無法通過名稱引用它。
您可以在此處閱讀有關服務的DNS記錄的更多信息
此外,Kubernetes還具有“服務發現”功能,可將服務的端口和ips暴露在部署到同一名稱空間的任何容器中。
解
這意味着,要達到hello-def,你可以這樣做
curl http://hello-def-service:${HELLO_DEF_SERVICE_PORT}
基於服務發現https://kubernetes.io/docs/concepts/services-networking/service/#environment-variables
警告 :如果服務端口發生更改,則很可能只有在同一命名空間中更改后創建的pod才會收到新的環境變量。
外部訪問
此外,只要您可以從外部訪問NodePort范圍,您就可以在外部使用NodePort功能從外部獲得此服務。
這將要求您通過node-ip:nodePort訪問您的服務
你可以找到隨機分配給你的服務的NodePort,用kubectl describe svc/hello-def-service
入口
要從外部訪問您的服務,您應該實現入站服務,例如nginx-ingress
https://github.com/helm/charts/tree/master/stable/nginx-ingress https://github.com/kubernetes/ingress-nginx
邊門
如果您的2項服務緊密耦合,您可以使用Kubernetes Sidecar功能將它們包含在同一個pod中。 在這種情況下,pod中的兩個容器將共享相同的虛擬網絡適配器,並可通過localhost:$port
https://kubernetes.io/docs/concepts/workloads/pods/pod/#uses-of-pods
服務發現
當Pod在節點上運行時,kubelet為每個活動服務添加一組環境變量。 它支持Docker鏈接兼容變量(請參閱makeLinkVariables)和更簡單的{SVCNAME} _SERVICE_HOST和{SVCNAME} _SERVICE_PORT變量,其中服務名稱為大寫,短划線轉換為下划線。
在此處閱讀有關服務發現的更多信息: https : //kubernetes.io/docs/concepts/services-networking/service/#environment-variables
您應該能夠通過DNS在hello-abc
通過pod獲取hello-def-service
,如下所示: https : //kubernetes.io/docs/concepts/services-networking/dns-pod-service/#services
但是,在群集中使用DNS記錄之前,必須在k8s群集中配置/安裝kube-dns
或CoreDNS
。
具體來說,您應該達到hello-def-service
通過DNS記錄http://hello-def-service
在相同的命名空間運行服務hello-abc-service
您應該能夠通過DNS記錄hello-def-service.other_namespace.svc.cluster.local
在另一個名稱空間ohter_namespace
運行hello-def-service
。
如果由於某種原因,您沒有在群集中安裝DNS加載項,您仍然可以通過hello-abc
pod中的環境變量找到hello-def-service
的虛擬IP。 正如此處所述 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.