Search code examples
kuberneteskubernetes-ingress

How to forward k8s ingress domain to backend server with uri?


I want to use k8s ingress to forward the domain to some service with URI. The ingress yaml just like as below:

- host: foo.example
  http:
    paths:
    - backend:
        path: /
        pathType: Prefix
        service:
          name: serviceA
          port:
            number: 8999
          path: /foo/bar # don't have this attribute, but I want something like this
      

I found the k8s documents say the path attribute in paths can do this:

  • foo.example/foo -> serviceA:8999
  • foo.example/bar -> serviceB:9888

But I want to do this: foo.example -> serviceA:8999/foo/bar. The same thing in nginx config is:

server {
    server_name foo.example;
    location / {
      proxy_pass http://service:8999/foo/bar;
    }
}

How could I do in the k8s ingress? Thanks.


Solution

  • Nginx Ingress controller supports rewrites and code snippets. I think what you want can be done by annotations. From the example here https://kubernetes.github.io/ingress-nginx/examples/rewrite/ your code should look like:

    apiVersion: networking.k8s.io/v1
    kind: Ingress
    metadata:
      annotations:
        nginx.ingress.kubernetes.io/rewrite-target: /foo/bar/$1
      name: <ingress-name>
      namespace: <namespace>
    spec:
      ingressClassName: nginx
      rules:
      - host: fool.example
        http:
          paths:
          - path: /(.*)
            pathType: Prefix
            backend:
              service:
                name: serviceA
                port: 
                  number: 8999
    

    You can add even more complex behavior (like your nginx config) with server snippets:

    https://github.com/kubernetes/ingress-nginx/blob/main/docs/user-guide/nginx-configuration/annotations.md#server-snippet