Skip to content
Advertisement

Spring boot cannot connect to postgre database deployed on another kubernetes pod

I deployed my microservice hello-k8s in a pod and another pod as postgre-server, I have successfully connected to localhost using port-forward and try to create a table in the deployed database. But when I deploy hello-k8s it return error due to database connection attempt failed.

Disclaimer: kube-dns is working fine, I already try nslookup to the postgre-svc and it works well.

Here is the error

Caused by: java.net.UnknownHostException: postgre-svc
at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:220) ~[na:na] at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:403) ~[na:na]
at java.base/java.net.Socket.connect(Socket.java:609) ~[na:na]
at org.postgresql.core.PGStream.(PGStream.java:81) ~[postgresql-42.2.12.jar:42.2.12]
at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:93) ~[postgresql-42.2.12.jar:42.2.12]
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:197) ~[postgresql-42.2.12.jar:42.2.12]

Here is the application.yml file

JavaScript

Here is the configuration code to connect to database

JavaScript

Here is the postgre service

JavaScript

Here is my hello-k8s.yml deployment

JavaScript

I have feeling it is due to HikariConfig, but I haven’t found any reference yet for that. anyway, anyone in the world has face issue like this? Feel blessed if anyone can help or have advice 🙂

Advertisement

Answer

Your client Deployment is explicitly labeled to deploy into a different namespace, but the database Service isn’t. By default this will cause the database Service to get deployed into the default namespace; the two objects being in different namespaces will cause the DNS issue you’re getting.

I typically don’t include an explicit namespace: in my Kubernetes YAML files. Instead, I use the kubectl --namespace option if I want to install things in a specific namespace. This also makes it a little easier to reuse a set of YAML files in a slightly different context.

You should also be able to make this work by pointing at the Service in the default namespace; set PG_SERVER to postgre-svc.default or postgres-svc.default.svc.cluster-local, including the other namespace name in the DNS name. (The database’s StatefulSet object also needs to be in the same namespace as its Service, so double-check that they’re correctly deployed together.)

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement