Kubernetes/Helm ingress path with nginx and regex

8/1/2017

We have a number of micro services in our eco system and a two of them deal with user data:

  • user service ->

    • POST /users
    • GET /users/[[:alnum:]]+
  • documents service ->

    • POST /users/[[:alnum:]]+/documents
    • GET /users/[[:alnum:]]+/documents/[[:alnum:]]+

Therefore I wanted to define this in an Ingress:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: {{.Release.Name}}
  annotations:
    kubernetes.io/ingress.class: "nginx"
    kubernetes.io/tls-acme: "true"
    ingress.kubernetes.io/enable-cors: "false"
    ingress.kubernetes.io/ssl-redirect: "true"
  labels:
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    app: "{{ template "fullname" . }}"
    heritage: "{{ .Release.Service }}"
    release: "{{ .Release.Name }}"
    tier: frontend
spec:
  tls:
  - secretName: {{ template "tls.fullname" . }}
    hosts:
    - "staging.ourhost.com"
  rules:
  - host: "staging.ourhost.com"
    http:
      paths:
    - path: "/users/[[:alnum:]]+"
      backend:
        serviceName: {{ .Values.api.services.user_service  | quote }}
        servicePort: 8080
    - path: "/users/[[:alnum:]]+/documents"
      backend:
        serviceName: {{ .Values.api.services.document_service | quote }}
        servicePort: 8888

This results in the following being set in ngix.conf:

location /users/[[:alnum:]]+ {
...
}

location /users/[[:alnum:]]+/documents{
...
}

i.e. the regex is not resolved.

I tried splitting it out into individual ingresses and using the annotation

ingress.kubernetes.io/rewrite-target: "/users/$1/documents"

but this resulted in the following in nginx.conf

location ~* ^/users/[[:alnum:]]+/documents/(?<baseuri>.*) {
            set $proxy_upstream_name "default-dev-document_service-8888";

  ...

    rewrite /users/[[:alnum:]]+/documents/(.*) /users/$1/documents/$1 break;
    proxy_pass http://default-dev-document_service-8888;

        }

Question (finally):

  • Why is $1 always appended? this seems strange to me
  • Does someone know another way to make paths work with regex?

Any advice would be greatly apreciated

-- Causteau
kubernetes
kubernetes-helm
nginx

1 Answer

11/12/2017

After lots of searching, it seems that what I was trying to do is not (yet) possible in ingress. I opened a PR with them and I am waiting to see if it will be merged.

I have not yet publicly deployed a version with this change available, but the branch can be build using the dev docs from k8s

-- Causteau
Source: StackOverflow