karina
karina

Reputation: 757

how to connect to database service using cluster ip

This might be very basic question but I can't find anywhere so I apologize..

I have installed postresql using helm on Google Kubernetes Engine

$ helm install --name staging stable/postgresql

My deployments:

$ kubectl get deployments
NAME                 DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
staging-backend      7         7         7            0           3h
staging-postgresql   1         1         1            0           3h

And my services:

$ kubectl get services
NAME                 TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)    AGE
staging-postgresql   ClusterIP   xx.x.xxx.xx   <none>        5432/TCP   3h

I tried to connect staging-backend with staging-postgresql using cluster IP but it doesn't seem to work. Or should I use external IP..?? Where can I find external IP..??

thank Youu..

Upvotes: 4

Views: 6284

Answers (1)

Adrian Farmadin
Adrian Farmadin

Reputation: 427

In Kubernetes you have two options to find IP of your service.

  1. Environment variables

Kubernetes generates automatically environment variables with all the data you need to access a service. If you run env command inside a pod, then you should see similar output to:

KUBERNETES_SERVICE_PORT=443
STAGING_POSTGRESQL_SERVICE_HOST=10.0.162.149
KUBERNETES_SERVICE_HOST=10.0.0.1
STAGING_POSTGRESQL_SERVICE_PORT=5432
KUBERNETES_SERVICE_PORT_HTTPS=443

Use STAGING_POSTGRESQL_SERVICE_HOST environment variable in your app to get the IP of service.

  1. DNS (preferred)

Kubernetes automatically assigns DNS names to all services. Use your service name instead of IP and it will be resolved to service IP.

For example run ping staging-postgresql inside any pod.

You can read more about using service here.

Upvotes: 6

Related Questions