How can a Kubernetes pod connect to database which is running in the same local network (outside the cluster) as the host?

9/30/2019

I have a Kubernetes cluster (K8s) running in a physical server A (internal network IP 192.168.200.10) and a PostgreSQL database running in another physical server B (internal network IP 192.168.200.20). How can my Java app container (pod) running in the K8s be able to connect to the PostgreSQL DB in server B?

OS: Ubuntu v16.04 Docker 18.09.7 Kubernetes v1.15.4 Calico v3.8.2 Pod base image: openjdk:8-jre-alpine

I have tried following this example to create a service and endpoint

kind: Service
apiVersion: v1
metadata:
 name: external-postgres
spec:
 ports:
 - port: 5432
   targetPort: 5432
---
kind: Endpoints
apiVersion: v1
metadata:
 name: external-postgres
subsets:
 - addresses:
     - ip: 192.168.200.20
   ports:
     - port: 5432

And had my JDBC connection string as: jdbc:postgresql://external-postgres/MY_APPDB , but it doesn't work. The pod cannot ping server B or telnet the DB using the said internal IP or ping external-postgres service name. I do not wish to use "hostNetwork: true" or connect server B via a public IP.

Any advice is much appreciated. Thanks.

-- Wuahaha
calico
docker
kubernetes
networking
postgresql

2 Answers

10/2/2019

I guess you can replace CALICO_IPV4POOL_CIDR without re-spawning K8s cluster via kubeadm builder tool, maybe it can be useful in some circumstances.

Remove current Calico CNI plugin installation, eg.:

$ kubectl delete -f https://docs.projectcalico.org/v3.8/manifests/calico.yaml

Install Calico CNI addon, supplying CALICO_IPV4POOL_CIDR parameter with a desired value:

$ curl -k https://docs.projectcalico.org/v3.8/manifests/calico.yaml --output some_file.yaml && sed -i "s~$old_ip~$new_ip~" some_file.yaml && kubectl apply -f some_file.yaml

Re-spin CoreDNS pods:

$ kubectl delete pod --selector=k8s-app=kube-dns -n kube-system

Wait until CoreDNS pods obtain IP address from a new network CIDR pool.

-- mk_sta
Source: StackOverflow

10/1/2019

I just found out the issue is due to the K8s network conflict with the server local network (192.168.200.x) subnet.

During the K8s cluster initialization

kubadmin init --pod-network-cidr=192.168.0.0/16

The CIDR 192.168.0.0/16 IP range must be change to something else eg. 10.123.0.0/16
And this IP range must be also changed in the calico.yaml file before applying the Calico plugin:

# The default IPv4 pool to create on startup if none exists. Pod IPs will be
# chosen from this range. Changing this value after installation will have
# no effect. This should fall within `--cluster-cidr`.
  - name: CALICO_IPV4POOL_CIDR
    value: "10.123.0.0/16"

Can now ping and telnet server B after reset and re-init the K8s cluster with the different CIDR.

-- Wuahaha
Source: StackOverflow