Kubernetes: How to link to internal services with different namespaces?

10/1/2019

I am trying to link together two Kubernetes Services located in different namespaces like this. Linking them over DNS, with type ExternalName.

In namespace called "db" I wish to have a Deployment with a database. To be able to have 1 database that can be shared by different projects. To have one Persistent Volume.

But somehow it does not work like expected.

Service inside namespace "db":

apiVersion: v1
kind: Service
metadata:
  labels:
    app: db-srv
  name: db-srv
  namespace: db
spec:
  ports:
  - name: "db-postgres"
    port: 5432
    targetPort: 5432
  selector:
    app: db
status:
  loadBalancer: {}

Service located in "myspace"-namespace that connects to db:

apiVersion: v1
kind: Service
metadata:
  labels:
    app: myspace-db-service
  name: myspace-db-service
  namespace: myspace
spec:
  type: ExternalName
  externalName: db-srv.db.svc.cluster.local
  ports:
  - port: 5433
    # targetPort: 5432
status:
  loadBalancer: {}

The backend attaches to myspace-service on Port 5433.

Are the ports wrong?

-- Espen Finnesand
kubernetes
kubernetes-service

1 Answer

10/2/2019

The answer is that ports on the Service with ExternalType and the Service that it connects to need to be the same. Using targetPort on the ExternalType does not work.

This is correct:

SVC(externalType) => PORT (5433) => SVC(other namespace) on PORT(5433) => targetPort

This is NOT correct:

SVC(externalType) => PORT (5433) => TARGETPORT (5432) => SVC(other namespace) on PORT(5432) => targetPort

-- Espen Finnesand
Source: StackOverflow