How get public ip for kubernetes pod?

1/29/2017

The question: I have a VOIP application running in a kubernetes pod. I need to set in the code the public IP of the host machine on which the pod is running. How can I get this IP via an API call or an environmental variable in kubernetes? (I'm using Google Container Engine if that's relevant.) Thanks a lot!

Why do I need this? The application is a SIP-based VOIP application. When a SIP request comes in and does a handshake, the application needs to send a SIP invite request back out that contains the public IP and port which the remote server must use to set up a RTP connection for the audio part of the call.

Please note: I'm aware of kubernetes services and the general best-practise of exposing those via a load balancer. However I would like to use hostNetwork=true and expose ports on the host for the remote application to send RTP audio packets (via UDP) directly. This kubernetes issue (https://github.com/kubernetes/kubernetes/issues/23864) contains a discussion of various people running SIP-based VOIP applications on kubernetes and the general concessus is to use hostNetwork=true (primarily for performance and due to limitations of load balancing UDP I believe).

-- mleonard
google-kubernetes-engine
kubernetes

1 Answer

1/29/2017

You can query the API server for information about the Node running your pod like it's addresses. Since you are using hostNetwork=true the $HOSTNAME environment variable identifies the node already.

There is an example below that was tested on GCE.

The code needs to be run in a pod. You need to install some python dependencies first (in the pod):

pip install kubernetes

There is more information available at: https://github.com/kubernetes-incubator/client-python

import os
from kubernetes import client, config

config.load_incluster_config()
v1=client.CoreV1Api()
for address in v1.read_node(os.environ['HOSTNAME']).status.addresses:
    if address.type == 'ExternalIP':
        print address.address
-- Janos Lenart
Source: StackOverflow