Kubernetes how to run multiple services at the same address

8/25/2021

I have several sites available at http://service1/api and http://service2/api I want them to work on the same external address and routing occurs inside the kube

http:/exturi/service1/api
http:/exturi/service2/api

Ingress configuration

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: haproxy
  name: ingress-api
spec:
  rules:
  - host: api.sample.com
    http:
      paths:
      - backend:
          serviceName: edpcore-db-api
          servicePort: 13001
        path: /db-api/
        pathType: Prefix
  tls:
  - hosts:
    - api.sample.com
    secretName: tls-api-secret

how to configure ingress

-- Nikolay Sulimov
haproxy
kubernetes
kubernetes-ingress

2 Answers

8/25/2021

Thats how you should do it (nginx ingress):

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: my-ingress
  namespace: my-ingress-namespace
spec:
  rules:
  - host: exturi
    http:
      paths:
      - backend:
          service:
            name: service1
            port:
              number: 80
        path: /service1/(.*)
        pathType: ImplementationSpecific      
      - backend:
          service:
            name: service2
            port:
              number: 80
        path: /service2/(.*)
        pathType: ImplementationSpecific
status:
  loadBalancer:
    ingress:
    - ip: {}
-- Dani Alderete
Source: StackOverflow

8/25/2021

If you are using the Nginx ingress you can do routing using

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
  name: rewrite
  namespace: default
spec:
  rules:
  - host: rewrite.bar.com
    http:
      paths:
      - backend:
          serviceName: service-1
          servicePort: 80
        path: /service-1(/|$)(.*)
      - backend:
          serviceName: service-2
          servicePort: 80
        path: /service-2(/|$)(.*)

For example, the ingress definition above will result in the following rewrites:

rewrite.bar.com/service1 rewrites to rewrite.bar.com/
rewrite.bar.com/service1/ rewrites to rewrite.bar.com/
rewrite.bar.com/service1/new rewrites to rewrite.bar.com/new

Refer : https://kubernetes.github.io/ingress-nginx/examples/rewrite/

Extra

If you don't want to remove service name or rewrite simple use this config

    apiVersion: networking.k8s.io/v1
    kind: Ingress
    metadata:
      annotations:
        kubernetes.io/ingress.class: haproxy
      name: simple
      namespace: default
    spec:
      rules:
      - host: simple.bar.com
        http:
          paths:
          - backend:
              serviceName: service-1
              servicePort: 80
            path: /service-1
          - backend:
              serviceName: service-2
              servicePort: 80
            path: /service-2
-- Harsh Manvar
Source: StackOverflow