Contact host port from inside Kubernetes pod

2/20/2020

I have a Kubernetes Pod (controlled by a DaemonSet) that needs to communicate with a daemon that belongs to the Weave Net CNI plugin and serves HTTP at localhost:6784.

In order to communicate with this server from inside the pod, do I have to equip it with hostnetwork: true, or is there another (better) way to do this?

I'm asking because in general hostnetwork: true should be avoided, plus it also makes it more complicated for the pod to reach the Kubernetes API (which it also needs to do).

-- rookie099
kubernetes

1 Answer

2/21/2020

Since no better way became apparent, I'm now running the pod with hostNetwork: true. Its container mounts the host's file /etc/kubernetes/kubelet.conf, and it parses and employs the Kubernetes server URL as follows:

with open('/etc/kubernetes/kubelet.conf', 'r') as stream:
  config = yaml.safe_load(stream)
current_context = config['current-context']
context = next(context for context in config['contexts'] if context['name'] == current_context)
cluster = next(cluster for cluster in config['clusters'] if cluster['name'] == context['context']['cluster'])
server = cluster['cluster']['server']

k8s_configuration = kubernetes.client.Configuration()
k8s_configuration.host = server
k8s_configuration.ssl_ca_cert = '/run/secrets/kubernetes.io/serviceaccount/ca.crt'
k8s_configuration.api_key_prefix['authorization'] = 'Bearer'
with open('/run/secrets/kubernetes.io/serviceaccount/token', 'r') as stream:
  k8s_configuration.api_key["authorization"] = stream.read()
k8s_client = kubernetes.client.ApiClient(k8s_configuration)

I am not using kubernetes.config.load_kube_config() to do the parsing, because it wants further credentials, such as /var/lib/kubelet/pki/kubelet-client-current.pem, which are not (and in this context should not be) mounted.

-- rookie099
Source: StackOverflow