Routing URLs to OpenFaaS functions

OpenFaaS exposes functions under the path https://[gateway]/function/[function name]. However, this might not always be suitable so you might want to route a different URL directly to a specific function.

One way to do so is running your own proxy that takes care of routing, but for some use-cases that may be a bit too much. What we will do in this post is create an Ingress for each path that we want to be routed to a function. For example, say we have two functions:

  1. sentimentanalysis
  2. nodeinfo

and we want to route the following URLs:

  • https://sentiment.domain.tld/ → function sentimentanalysis
  • https://sentiment.domain.tld/nodeinfo → function nodeinfo

For each one of those URLs,  we will proxy the connections to the OpenFaaS gateway. OpenFaaS uses the first part of the URL path (/function/[function name]) to identify the function, so we will also set the function name manually.

An Ingress config for the routes listed above would look like this:

sentiment.domain.tld, sentimentanalysis

---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: sentiment-domain-tld
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: "/function/sentimentanalysis"
  namespace: openfaas
spec:
  rules:
  - host: sentiment.domain.tld
    http:
      paths:
      - path: /
        backend:
          serviceName: gateway
          servicePort: 8080

sentiment.domain.tld/nodeinfo, nodeinfo

---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: sentiment-domain-tld-nodeinfo
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: "/function/nodeinfo"
  namespace: openfaas
spec:
  rules:
  - host: sentiment.domain.tld
    http:
      paths:
      - path: /nodeinfo
        backend:
          serviceName: gateway
          servicePort: 8080

The important bits to note are:

  • namespace: openfaas we need access to OpenFaaS's gateway service, so our Ingresses need to be on its namespace
  • nginx.ingress.kubernetes.io/rewrite-target: "/function/nodeinfo" OpenFaaS needs to know what functions we are invoking—this is where we manually set the function name. The original path is preserved and appended.