Nimander
Nimander

Reputation: 77

How to connect to service/prometheus-operated from python flask app in kubernetes

I have a prometheus on my kuberetes with prometheus-operated service

NAME                       TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)       AGE
prometheus-operated        ClusterIP   None             <none>        9090/TCP      13d

and a flask app deployment

NAME                         READY   STATUS    RESTARTS   AGE
flask-app-7d59898b78-2j59f   1/1     Running   0          23m

I want to connect to prometheus-operated from my app by sending get request

URL = "http://localhost:9090/api/v1/query_range"
PROMQL = ...
r1 = requests.get(url=URL, params=PROMQL)

but I'm getting Connection Refused errors

ConnectionError: HTTPConnectionPool(host='localhost', port=9090): Max retries exceeded with url: /api/v1/query_range?query= <<<my long query here>>>  (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fbbc01b6d60>: Failed to establish a new connection: [Errno 111] Connection refused'))

When i run my flask app outside of kubernetes the connection works fine. What is the correct URL to connect to prometheus-operated?

Upvotes: 0

Views: 203

Answers (1)

Arash
Arash

Reputation: 340

If both Prometheus and your flask app are deployed in the same namespace, you can use the service name prometheus-operated to connect to it.

URL = "http://prometheus-operated:9090/api/v1/query_range"

or in case of a different namespace, assuming you don't have network policies in place and your cluster is deployed with Kube DNS: The Kube-DNS naming convention is service.namespace.svc.cluster-domain.tld and the default cluster domain is cluster.local.

For example, if you want to contact a service called mysql in the db namespace from any namespace, you can simply speak to mysql.db.svc.cluster.local.

So:

URL = "http://prometheus-operated.$PROM_NAMESPACE.svc.cluster.local:9090/api/v1/query_range"

Upvotes: 1

Related Questions