Search code examples
kubernetesconsulregistrator

Getting IP into env variable via DNS in kubernetes


I'm trying to get my head around K8s coming from docker compose. I would like to setup my first pod with two containers which I pushed to a registry. Following question:

How do I get the IP via DNS into a environment variable, so that registrator can connect to consul? See container registrtor in args consul://consul:8500. The consul needs to be changed with the env.

{
  "kind": "Pod",
  "apiVersion": "v1",
  "metadata": {
    "name": "service-discovery",
    "labels": {
      "name": "service-discovery"
    }
  },
  "spec": {
    "containers": [
      {
        "name": "consul",
        "image": "eu.gcr.io/{myproject}/consul",
        "args": [
          "-server",
          "-bootstrap",
          "-advertise=$(MY_POD_IP)"
        ],
        "env": [{
          "name": "MY_POD_IP",
          "valueFrom": {
            "fieldRef": {
              "fieldPath": "status.podIP"
            }
          }
        }],
        "imagePullPolicy": "IfNotPresent",
        "ports": [
          {
            "containerPort": 8300,
            "name": "server"
          },
          {
            "containerPort": 8400,
            "name": "alt-port"
          },
          {
            "containerPort": 8500,
            "name": "ui-port"
          },
          {
            "containerPort": 53,
            "name": "udp-port"
          },
          {
            "containerPort": 8443,
            "name": "https-port"
          }
        ]
      },
      {
        "name": "registrator",
        "image": "eu.gcr.io/{myproject}/registrator",
        "args": [
          "-internal",
          "-ip=$(MY_POD_IP)",
          "consul://consul:8500"
        ],
        "env": [{
          "name": "MY_POD_IP",
          "valueFrom": {
            "fieldRef": {
              "fieldPath": "status.podIP"
            }
          }
        }],
        "imagePullPolicy": "Always"
      }
    ]
  }
}

Solution

  • Exposing pods to other applications is done with a Service in Kubernetes. Once you've defined a service you can use environment variables related to that services within your pods. Exposing the Pod directly is not a good idea as Pods might get rescheduled.

    When e.g. using a service like this:

    apiVersion: v1
    kind: Service
    metadata:
      name: consul
      namespace: kube-system
      labels:
        name: consul
    spec:
      ports:
        - name: http
          port: 8500
        - name: rpc
          port: 8400
        - name: serflan
          port: 8301
        - name: serfwan
          port: 8302
        - name: server
          port: 8300
        - name: consuldns
          port: 8600
      selector:
        app: consul
    

    The related environment variable will be CONSUL_SERVICE_IP

    Anyways it seems others actually stopped using that environment variables for some reasons as described here