Default path on multiple nginx ingress rewrite

8/6/2018

Here is my situation, I'm on kubernetes (ingress), with two docker images: one dedicated to the web and the second one to the api.

Under the next configuration (at the end of the message): /web will show the front-end that will make some calls to /api, all good there.

but / is a 404 since nothing is defined, I couldn't find a way to tell in the ingress config that / should redirect to /web

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: dev-ingress
  annotations:
    kubernetes.io/tls-acme: "true"
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  tls:
  - hosts:
    - demo.com
    secretName: tls-secret
  rules:
  - host: demo.com
    http: 
      paths:
      - path: /api
        backend:
          serviceName: api-app
          servicePort: 8080
      - path: /web
        backend:
          serviceName: web-app
          servicePort: 80
-- Miguel Angel Acevedo
kubernetes
kubernetes-ingress

1 Answer

11/12/2018

This depends on what your frontend and backend apps expect in terms of paths. Normally the frontend will need to be able to find the backend on a certain external path and in your case it sounds like your backend needs to be made available on a different path externally (/api) from what it works on within the cluster (/). You can rewrite the target for requests to the api so that /api will go to / when the request is routed to the backend:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: dev-ingress-backend
  annotations:
    kubernetes.io/tls-acme: "true"
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  tls:
  - hosts:
    - demo.com
    secretName: tls-secret
  rules:
  - host: demo.com
    http: 
      paths:
      - path: /api
        backend:
          serviceName: api-app
          servicePort: 8080

And you can also define a separate ingress (with a different name) for the frontend that does not rewrite the target, so that a request to /web will go to /web for it:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: dev-ingress-frontend
  annotations:
    kubernetes.io/tls-acme: "true"
spec:
  tls:
  - hosts:
    - demo.com
    secretName: tls-secret
  rules:
  - host: demo.com
    http: 
      paths:
      - path: /web
        backend:
          serviceName: web-app
          servicePort: 80
-- Ryan Dawson
Source: StackOverflow