Cannot connecto to external database from inside kubernetes pod

10/2/2019

I am trying to connect my spring-boot api inside a kubernetes pod to an external database (a separate machine but within the local network), however when running, I get SQLNonTransientConnectionException, UknownHostException: mysql-svc, the api cannot connect to the database but whenever I ping the database address from inside the pod using kubectl exec -it, I can ping it successfully, anybody who has experienced the same error as mine?

here is my application.properties connection uri and kubernetes objects:

spring.datasource.url=jdbc:mysql://mysql-svc/test?autoReconnect=true

---
apiVersion: v1
kind: Service
metadata:
 name: mysql-svc
spec:
 type: ClusterIP
 ports:
 - port: 3306
   targetPort: 3306
---
apiVersion: v1
kind: Endpoints
metadata:
 name: mysql-svc
subsets:
 - addresses:
   - ip: 10.0.123.28
   ports:
   - port: 3306
     name: mysql-svc
-- Anthony
docker
java
kubernetes
mysql
spring-boot

3 Answers

10/4/2019

After hours of digging and reconfiguring, I finally get it to work, thanks to Xenwar from kubernetes group for pointing out the externalIP property, it turns out that i need to point my app to an external ip, in this case the database, here is the service object:

apiVersion: v1
kind: Service
metadata:
  name: db-con
spec:
  selector:
    app: api2
  ports:
    - name: http
      protocol: TCP
      port: 3306
      targetPort: 3306
  externalIPs:
    - 10.0.123.28
-- Anthony
Source: StackOverflow

10/2/2019

You service is not a "headless" service. Set the IP to None:

spec:
  clusterIP: None
  ports:
   - port: 3306
     targetPort: 3306

https://kubernetes.io/docs/concepts/services-networking/service/#headless-services

-- Burak Serdar
Source: StackOverflow

10/3/2019

If I understand you correctly you need a ExternalName service type.

ExternalName: Maps the Service to the contents of the externalName field (e.g. foo.bar.example.com), by returning a CNAME record with its value. No proxying of any kind is set up.

Here is an example:

apiVersion: v1
kind: Service
metadata:
  name: my-service
  namespace: prod
spec:
  type: ExternalName
  externalName: my.database.example.com

When looking up the host my-service.prod.svc.cluster.local, the cluster DNS Service returns a CNAME record with the value my.database.example.com. Accessing my-service works in the same way as other Services but with the crucial difference that redirection happens at the DNS level rather than via proxying or forwarding.

Please let me know if that helped.

-- OhHiMark
Source: StackOverflow