Kong — Creating a fallback route
Fed up of Kongs generic “no Route matched with those values”? I was!
I decided to read the documentation on how to create a fallback route, if a route isn’t matched. It’s a safe to say it was difficult to find the right information, the Kong docs are really good! but very extensive.
The journey was dangerous with indentation errors and outdated documentation, round every corner! I had to tread carefully…
It was Sunday, the weather was grey, office cold, the elements were against me… but as usual, I got stuck in and with a little logic and trial and error, I got it working.
To achieve a fallback we need to essentially do two steps:
- Define a fallback service
- Define an ingress that acts as an upstream. I.E when a request doesn’t match any route, default to the ingress that doesn’t have any routes defined, so it’ll just route to the service.
Here is a practical example, none of this demo s***t
Fallback Service
---apiVersion: apps/v1kind: Deploymentmetadata:name: fallback-svcnamespace: appspec:replicas:selector:matchLabels:app: fallback-svctemplate:metadata:labels:app: fallback-svcspec:containers:- image: 12345678910112.dkr.ecr.eu-west-2.amazonaws.com/app:v1.0 #getting the docker image from aws ecr. You can relace this with #whatever you use to store your images. I use ecr as it works really #well with automated deployments via GitHub actions.imagePullPolicy: Alwaysname: fallback-svcports:- containerPort: 80livenessProbe:tcpSocket:port: 80initialDelaySeconds: 30periodSeconds: 5timeoutSeconds: 2resources:limits:cpu: 512mmemory: 1024Mirequests:cpu: 256mmemory: 512Mi---apiVersion: v1kind: Servicemetadata:namespace: appname: fallback-svcspec:type: NodePort #allow external traffic to each my service.selector:app: fallback-svcports:- port: 80targetPort: 80protocol: TCP
The upstream — fallback
apiVersion: extensions/v1beta1kind: Ingressmetadata:name: fallback-ing-svcnamespace: appannotations:kubernetes.io/ingress.class: kongspec:rules:- http:paths:- backend:serviceName: fallback-svcservicePort: 80
To see the manifests with correct indentation etc see repo: https://github.com/jjcallis/kong-fallback-service
So what does it do? In a nutshell, the fallback service using the Ingress resource, will receive all requests that don’t match against any of your defined rules within a different Ingress. such as
apiVersion: extensions/v1beta1kind: Ingressmetadata:name: ing-onenamespace: appannotations:kubernetes.io/ingress.class: kongspec:hosts:- example.comrules:- host: example.com- http:paths:- path: /healthbackend:serviceName: app-nginxservicePort: 80- path: /api/v1/awesomebackend:serviceName: app-nginxservicePort: 80
So, when none of the above routes are matched. Your ‘upstream’ service will kick in and route all traffic to your app for you to handle the route not found how you like and removes the default “no Route matched with those values” that kong does.