简体   繁体   中英

How to access the service ip in kubernetes by name?

Say if I have a rabbitmq service as follows:

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? In other words what should go to the value: XXXXXXXXXX in the second deployment yaml. (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). Any advice is welcome!

kubernetes injects environment variables for a service's host, port, protocol among others into pod containers (see this doc ).

kubectl exec <pod> printenv is one way to check which env variables are set.

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.

The convention is typically uppercase <SERVICE_NAME>_SERVICE_HOST . You can set it explicitly in a pod spec using the following syntax.

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

Bear in mind the variable is already injected by k8s and this is just aliasing it. You may want to update your reference in the application layer /script to use the k8s injected environment variable for the service.

Reading between the lines (and I hope this helps):

K8s automatically creates service environment variables for you inside each pod. See https://kubernetes.io/docs/concepts/services-networking/service/#environment-variables for details.

The other route is to enable kube dns, in which case one can contact a service IP simply by using the service name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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