kubernetesmicrok8skube-dns

Host node address (alias or static ip?) from inside containers


What is the correct way to address a host node from inside containers?

I have a container that resides on a host node, and the host node has a web server running on it. The container needs to be able to hit web server on the host node.

I expected to find an alias for the host node like node..cluster.local (10.1.111.192), but I can't find it in the documentation.

The environment is microk8s with kubedns enabled.

Drawing

The address assigned to the host on the calico interface is accessible from inside the node: 10.1.111.192 and I found in the documentation that I can add a hostalias-pod, so I could add the alias, eg. node.local (10.1.111.192). https://kubernetes.io/docs/tasks/network/customize-hosts-file-for-pods/

Hardcoding the IP doesn't seem graceful, but I'm in a single-node environment, so it's not likely to matter if the node address doesn't change (does this ever change?). This is a small project where I'm trying to learn though, so I wanted to find the most correct way to do this.


Solution

  • You can use the downward API to get the underlying hostname, worth to mention that it will return the IP of the node where the pod is running on.

          env:
            - name: HOST_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.hostIP
    

    so from inside pod, you will be able to reach that particular host

    curl $HOST_IP:8080
    

    A complete example

    apiVersion: v1
    kind: Pod
    metadata:
      name: print-host-ip
    spec:
      containers:
        - name: print-host-ip
          image: gcr.io/google_containers/busybox
          env:
            - name: HOST_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.hostIP
          command: [ "/bin/sh", "-c", 'echo "host ip is $HOST_IP"' ]