Home > Net >  Dynamic Routing by Hostname only - Kubernetes Ingress Rules
Dynamic Routing by Hostname only - Kubernetes Ingress Rules

Time:04-01

I have a K8s cluster with multiple different services deployed and would like to use a single Ingress to route each incoming request to the appropriate service via a unique hostname DNS.

Currently, I've only been able to resolve a request when using the root path i.e. service-123.app.com.

As soon as I try to make a request with a path it doesn't resolve. The paths are valid paths to each service. For example, service-123.app.com/page/12345 would be expected by the application.

I might not fully understand how K8s Ingress rules are expected to work, but I hoped that it would match based on hostname only and simply forward on the path to the appropriate service.

Am I missing something very simple here? Any help is much appreciated. Thanks!

Here are my config files.

Ingress.yaml

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    ......
  name: app-name
  namespace: default
spec:
  rules:
  - host: service-123.app.com
    http:
      - path: "/*"
        backend:
          serviceName: service-123
          servicePort: 80
  - host: service-456.app.com
    http:
      paths:
      - path: "/*"
        backend:
          serviceName: service-456
          servicePort: 80

service.yaml

---
apiVersion: v1
kind: Service
metadata:
  annotations: {}
  labels:
    app: service-123
  name: service-123
  namespace: default
spec:
  ports:
  - name: port8080
    port: 80
    targetPort: 8080
  selector:
    app: service-123
  type: NodePort

CodePudding user response:

Not sure which K8s and ingress controller you are using, but in the later K8s you can specify the pathType which takes care of path wildcards more nicely.

You would have something like this:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    ......
  name: app-name
  namespace: default
spec:
  rules:
  - host: service-123.app.com
    http:
      - path: /
        pathType: Prefix
        backend:
          serviceName: service-123
          servicePort: 80
  - host: service-456.app.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          serviceName: service-456
          servicePort: 80

If you are using an nginx ingress controller a good way to see the right nginx configuration is by looking at the actual nginx.conf generated by the ingress controller.

$ kubectl cp <nginx-ingress-controller-pod>:nginx.conf nginx.conf
$ cat nginx.conf
  • Related