How to deploy spring boot app which uses postgres database on kubernetes?

5/31/2019

I used this command to deploy my spring boot application

sudo kubectl run mykubernetes-springboot 
--image=glgelopfalcon/springboot_docker_maven:0.0.1-SNAPSHOT --port=8080

Deplyment is created but when i check logs by

kubectl logs pod podname

It giving exception as

Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

I installed postgres on my local machine.

Test for semah answer postgres.yaml

kind: Service
apiVersion: v1
metadata:
  name: postgres-svc
  namespace: default
spec:
  type: ExternalName
  externalName: 10.0.2.2

kubectl get svc gives

postgres-svc       ExternalName   <none>           10.0.2.2      <none>           2m12s

Spring boot app deployement logs give

IOException occurred while connecting to postgres-svc.external.svc:5432
java.net.UnknownHostException: postgres-svc.external.svc
-- Dhanraj
kubernetes

1 Answer

5/31/2019

If you are trying to connect to DB installed on your local machine and not in kubernetes it is normal to have this error because localhost inside pod this not means your local machine , so can you tell where your db is running ?

try this as you confirmed that you run in local :

apiVersion: v1
kind: Service
metadata:
name: mysql-db-svc
spec:
ports:
- port: 5432

and add endpoint to this service :

apiVersion: v1
kind: Endpoints
metadata:
name: mysql-db-svc
subsets:
- addresses:
 - ip: 10.0.2.2
 ports:
 - port: 5432

then access it using :

url=jdbc:postgresql://mysql-db-svc/databasename
-- Semah Mhamdi
Source: StackOverflow