How to expose service with multiple port in one ingress with one 80 port

8/13/2020

I want to expose my two API service by ingress in one 80 port.

apiVersion: v1
kind: Service
metadata:
  name: my-api
spec:
  selector:
    app: my-api
  ports:
  - name: api1
    port: 3000
    targetPort: 3000
  - name: api2
    port: 4000
    targetPort: 4000
---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: app-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  tls:
  - hosts:
    - example.com
    secretName: app-tls
  rules:
  - host: example.com
    http:
      paths:
      - path: /my-api(/|$)(.*)
        backend:
          serviceName: my-api
          servicePort: 80

But when I try to reach the https://example.com/my-api, it always returns 503 status code.

-- ccd
kubernetes
kubernetes-ingress
nginx-ingress

1 Answer

8/13/2020

servicePort: 80 doesn't mean that the nginx ingress is serving on port 80. That's actually the port on your backend service, it sounds like you have 2 ports: 3000 and 4000.

The nginx ingress controller by default serves on port 80 and if you have TLS enabled also or/and 443. In your case, if you want to serve both APIs you can simply separate the paths.

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: app-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  tls:
  - hosts:
    - example.com
    secretName: app-tls
  rules:
  - host: example.com
    http:
      paths:
      - path: /my-api1(/|$)(.*)
        backend:
          serviceName: my-api
          servicePort: 3000
      - path: /my-api2(/|$)(.*)
        backend:
          serviceName: my-api
          servicePort: 4000

✌️

-- Rico
Source: StackOverflow