简体   繁体   中英

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.

Nginx Ingress controller supports rewrites and code snippets. I think what you want can be done by annotations. From the example here https://kube.netes.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/kube.netes/ingress-nginx/blob/main/docs/user-guide/nginx-configuration/annotations.md#server-snippet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM