using Pod environment variable to connect to pod

8/15/2020

In my AKS cluster I have 2 services (API and Redis DB). I want to connect to the Redis DB from the API pod.

I got the Redis Env using kubectl exec redis-pod -- printenv and the host variable is REDIS_SERVICE_HOST, is it possible to inject this env into the API deployment?

I tried something like this but it didn't work:

env:
   - name: REDIS_HOST
     value: ${REDIS_SERVICE_HOST}:6379
-- capiono
azure-aks
kubernetes

1 Answer

8/15/2020

You can store the redis host IP in a configMap and use that as env

  export REDISHOST_IP=XXX.XXX.XXX.XXX
  kubectl create configmap redishost --from-literal=REDISHOST=${REDISHOST_IP}

env:
- name: REDISHOST
  valueFrom:
    configMapKeyRef:
      name: redishost
      key: REDISHOST

A better approach would be to use kubernetes service to expose redis

apiVersion: v1
kind: Service
metadata:
  name: redis
  namespace: default
  labels:
    app: redis
  ports:
  - port: 6379
    targetPort: 6379
  selector:
    app: redis

Note: in this example the redis pod need to have label app: redis

Then inject redis.default.svc.cluster.local as redis host in other pods using env.

You also use configMap to store redis.default.svc.cluster.local and use it as env.

kubectl create configmap redishost --from-literal=REDISHOST=redis.default.svc.cluster.local

env:
- name: REDISHOST
  valueFrom:
    configMapKeyRef:
      name: redishost
      key: REDISHOST

This way even if redis pod is restarted and pod IP changes the other pods connecting to redis is not impacted and no change would be necessary.

-- Arghya Sadhu
Source: StackOverflow