Send TCP traffic to the ingress's namespace with Nginx Ingress

8/26/2019

I'm using an Nginx Ingress controller to open connections to a postgres database with the --tcp-services-configmap=k8s-ingress/k8s-ingress-tcp flag. That configmap looks like

apiVersion: v1
data:
  "5432": namespace-a/the-postgres-svc:5432
kind: ConfigMap

This portion works perfectly, however I would like to open up another service on the same port, 5432 to namespace-b/the-postgres-svc:5432.

Is there any way to have the namespace selected be based on the namespace from the ingress resource? Since the data key would be identical if I were to just add that record to the after the "namespace-a" record I am not able to just append to the configmap data.

Thanks!

-- politeauthority
kubernetes
nginx-ingress

1 Answer

8/27/2019

So you would like to have services on the same port in different namespaces. I have found interesting step-by-step tutorial for this approach.

Firstly you should create two namespaces:

apiVersion: v1
kind: Namespace
metadata:
  name: namespace-a

apiVersion: v1
kind: Namespace
metadata:
  name: namespace-b

Than have your services and deployment definition, where the difference is between name and namespace fields:

apiVersion: v1
kind: Service
metadata:
  labels:
    run: nginx
  name: namespacea-nginx
  namespace: namespace-a
spec:
  ports:
  - port: 5432
    protocol: TCP
    targetPort: 5432
  selector:
    run: nginx

apiVersion: v1
kind: Service
metadata:
  labels:
    run: nginx
  name: namespaceb-nginx
  namespace: namespace-b
spec:
  ports:
  - port: 5432
    protocol: TCP
    targetPort: 5432
  selector:
    run: nginx

Deployment files:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    run: nginx
  name: nginx
  namespace: namespace-a
spec:
  ...

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    run: nginx
  name: nginx
  namespace: namespace-b
spec:
  ...

And finally, Ingress files definitions:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: nginx-ingress
  namespace: namespace-a
  annotations:
    kubernetes.io/ingress.class: nginx
spec:
  rules:
  - host: namespacea.com
    http:
      paths:
      - backend:
          serviceName: namespacea-nginx
          servicePort: 5432
        path: /

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: nginx-ingress
  namespace: namespace-b
  annotations:
    kubernetes.io/ingress.class: nginx
spec:
  rules:
  - host: namespaceb.com
    http:
      paths:
      - backend:
          serviceName: namespaceb-nginx
          servicePort: 5432
        path: /
-- muscat
Source: StackOverflow