How to access postgresql pod/service in google kubernetes

7/15/2019

I am deploying a simple web application. I divided it into 3 pods:front end, back end, and postgres db. I successfully deployed my front end and back end to google kubernetes service and they works as expected. But for my postgresql db server, I used the following yamls. The postgres image is created by me using standard postgres images from dockerhub. I created some tables, and inserted some data and pushed to DockerHub. My backend is not able to make connection to my db. I think I might need to change my Java connection code.Not sure on using localhost. It works without any issue on my local Eclipse Jee and Tomcat.

//my pod.yaml
apiVersion: v1
kind: Pod
metadata:
   name: postgres-app-pod
   labels:
      name: postgres-app-pod
      app: demo-geo-app
spec:
   containers:
   - name: postgres
     image: myrepo/example:v1
     ports:
     - containerPort: 5432

//my service.yaml
apiVersion: v1
kind: Service
metadata:
   name: db
   labels:
      name: db-service
      app: demo-geo-app
spec:
   ports:
   - port: 5432
     targetPort: 5432
   selector:
      name: postgres-pod
      app: demo-geo-app 

   //from my java backend, I access my db server this way.
String dbURL = "jdbc:postgresql://localhost:5432/Location?user=postgres&password=mysecretpassword";
-- ENGLISH TEACHER
google-kubernetes-engine
java
kubernetes

2 Answers

7/15/2019

there are two issues to be fixed.

  1. the service selector key:value should match with pod labels
  2. replace localhost with postgresql service dns
-- P Ekambaram
Source: StackOverflow

7/15/2019

As per comments you have an error on your connection string, localhost is referring to the same pod where you are running the Java code, you need to change to db as the same name you put on the service yaml to work.

I recommend you to use a deployment instead of Pod on the type, but in that case that you are trying to deploy a database you need to use a StatefulSet please review the documentation

https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/

Also, I recommend you to check https://helm.sh you have a lot of chart ready to use instead of having to code from scratch a service like a database.

https://github.com/helm/charts/tree/master/stable/postgresql

On that chart you have all the necessary yaml ready including the PVC provisioning.

-- wolmi
Source: StackOverflow