How to access postgresql pod/service in google kubernetes

假如想象 提交于 2020-01-25 08:53:05

问题


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";

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/57038977/how-to-access-postgresql-pod-service-in-google-kubernetes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!