简体   繁体   English

如何按名称访问kubernetes中的服务IP?

[英]How to access the service ip in kubernetes by name?

Say if I have a rabbitmq service as follows: 说我是否有如下的rabbitmq服务:

apiVersion: v1
kind: Service
metadata:
  name: my-rabbitmq
spec:
  ports:
  - port: 6379
  selector:
    app: my-rabbitmq

And I have another deployment: 我还有另一个部署:

apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: A-worker
spec:
  replicas: 1
  containers:
  - name: a-worker
    image: worker-image
    ports:
    - containerPort: 80
    env:
    - name: rabbitmq_url
      value: XXXXXXXXXXXXX

Is there any way to set the service ip as environment variable in my second deployment by some kind of selector? 是否可以通过某种选择器在第二次部署中将服务ip设置为环境变量? In other words what should go to the value: XXXXXXXXXX in the second deployment yaml. 换句话说,第二个部署yaml中的value: XXXXXXXXXX应该为value: XXXXXXXXXX (Note I know I can get the service ip by kubectl get services , but I'd like to know how to set this by the service name or label). (请注意,我知道我可以通过kubectl get services获取服务ip,但是我想知道如何通过服务名称或标签来设置它)。 Any advice is welcome! 欢迎任何建议!

kubernetes injects environment variables for a service's host, port, protocol among others into pod containers (see this doc ). kubernetes将服务的主机,端口,协议等环境变量注入到pod容器中(请参阅此文档 )。

kubectl exec <pod> printenv is one way to check which env variables are set. kubectl exec <pod> printenv是检查设置了哪些env变量的一种方法。

If the service is created after the pod the env var may not be present so killing (restarting) the pod is one way to make sure the new environment variables are populated. 如果服务是在Pod之后创建的,则可能不存在env var,因此终止(重新启动)Pod是确保填充新环境变量的一种方法。

The convention is typically uppercase <SERVICE_NAME>_SERVICE_HOST . 约定通常为大写<SERVICE_NAME>_SERVICE_HOST You can set it explicitly in a pod spec using the following syntax. 您可以使用以下语法在pod规范中显式设置它。

  - name: rabbitmq_url value: $(MY-RABBITMQ_SERVICE_HOST) 

Bear in mind the variable is already injected by k8s and this is just aliasing it. 请记住,变量已由k8s注入,这只是对其进行别名。 You may want to update your reference in the application layer /script to use the k8s injected environment variable for the service. 您可能需要在应用程序层/ script中更新引用,以将k8s注入的环境变量用于服务。

Reading between the lines (and I hope this helps): 两行之间的阅读(希望对您有所帮助):

K8s automatically creates service environment variables for you inside each pod. K8s在每个吊舱内自动为您创建服务环境变量。 See https://kubernetes.io/docs/concepts/services-networking/service/#environment-variables for details. 有关详细信息,请参见https://kubernetes.io/docs/concepts/services-networking/service/#environment-variables

The other route is to enable kube dns, in which case one can contact a service IP simply by using the service name. 另一种方法是启用kube dns,在这种情况下,只需使用服务名称就可以联系服务IP。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM