Dynamically resolve a pods address for get request

12/3/2018

I got my application working in docker-compose, then converted it using kompose. However, I have a problem when I want to get data from the back-end. I can no longer use my previous method because of the url.

@app.route("/")
def home():
    url = "http://backend:5000/"
    try:
        res = requests.get(url)
    except Exception:
        return "Error with {}".format(url)
    dictFromServer = res.json()
    return dictFromServer['message']

What is the best way to get the url to work?

-- Annihil8
kubernetes
python

1 Answer

12/3/2018

The traditional way that is done is to use environment variables that are injected into your container's runtime. It is fine to have reasonable defaults so that local development can continue as it did before:

 import os

 def home():
     be_host = os.getenv('BACKEND_SERVICE_HOST', 'backend')
     be_port = os.getenv('BACKEND_SERVICE_PORT', '5000')
     url = 'http://{}:{}'.format(be_host, be_port)

Those environment variables and their values are injected by kubelet based on the name of the Service objects in the current namespace as the running Pod. In that example above, it would mean a Service was named backend and that service exposed a ports: on 5000 (pointing at whatever the exposed containerPorts: on the Pod itself.

You can, of course, declare your own environment variables, if that's too much magic for your team.

-- mdaniel
Source: StackOverflow