Migrating to GatewayAPI with Envoy Gateway
Today I will be performing a very common migration in this industry. I am going to be migrating from K8s Ingress to the new, fancy, schmancy Gateway API. [1] My current Ingress Controller is NGINX, which is going to make this quite a bit more brutal. Since NGINX Ingress Controller is now EOL, they will not implement this API on the newest versions. There is none! [2] If you use something like Traefik, you will be able to try it out without having to take down the existing Ingress infrastructure.
Choosing the right implementation
The first step before starting this migration is to choose the proper implementation for the Gateway API. Lets look at the docs! [3] So from the official K8s list of implementations, we will only look at the comformant implementations. Lets make a table with all available as off writing and their ups/downs:
| Gateway API Implementation | Pros | Cons |
|---|---|---|
| Agentgateway | AI application focus, MCP ingress. | LLM serving focus. Maybe a future goal. |
| Airlock Microgateway | Security focused with WAF built in. | Resource intensive. Increased latency for LAN applications. |
| Cilium | eBPF speeds for non L7 routes. Cillium CNI. | Time consuming, out of scope. L7 is just Envoy. |
| Envoy Gateway (GA) | Lightweight standard. The reference implementation of Gateway API. | No big ones, just not as fully automated as the other projects which wrap it. |
| Google Kubernetes Engine (GA) | Not applicable | Not applicable |
| HAProxy Ingress | Lightweight, incredibly high TCP throughput. | Might be a bit overcomplicated for our purposes. |
| Istio (GA) | Incredibly complete. Permits stepwise migration. | No big ones, Istio is incredibly good. |
| kgateway (GA) | Actively developed new player. | Smaller community, yet to be proclaimed as a standard. |
| NGINX Gateway Fabric (GA) | Still OSS NGINX under the hood. | Same NGINX constraints as always. |
| Traefik Proxy (GA) | Very standard ingress controller. Permits stepwise migration. | No big ones, I like Traefik. |
Look at that! There is not a single option I wouldn't like to try. Airlock's integrated WAF features are astounding. Agentgateway looks revolutionary for standardizing AI workflows, which I want to get into in the future. Cillium is simply, an incredible CNI with breathtaking architecture and features. But for this first raw dive into the Gateway API, I believe I am going to go with standard, Envoy Gateway. Mostly because other options are just wrappers around Envoy, so this is the base I should learn about.
Requirements
Something to keep in mind when making such a massive migration is our requirements. What features do I not want to lose? And what features do I need to make sure to add to make this worth it? For this migration to be considerered a succes we require:
- Expose HTTP applications with strong SNI routing
- Perform TLS termination at the ingress level with cert-manager integration
- Perform OIDC user authentication when JWT is not present
- Perform mTLS client side authentication to an external downstream
- For non HTTP, TCP Routes need to be easily created WITH SNI [4]
- Possibility of WAF on a per route basis
Installation
Now that we know what we need to implement for this migration. We can begin with the installation. Then we will start integrating some services. The idea is that we will have NGINX Ingress running parallely, as we perform this migration so that we dont lose our existing routes.
For installing Envoy Gateway there are various paths to take, up to administrator preference. [5] But since I am an ArgoCD fanatic, an Argo-nian if I might add, I followed the Argo CD installation with some of my own tweaks. These tweaks ironically, can all be found in the helm installation guide in Envoy Gateway's documentation. The first tweak, is creating Argo applications for each CRD chart. This will be extremely annoying in the future, I know. But with wanting to try out different implementations I wanted to separate them. This way I could have multiple implementations running at some point!
For the Gateway API CRDs, it is recommended that we use the experimental chart. And given our requirements stated above, we require using TLSRoutes and maybe even TCPRoutes, which are for now, expermiental. The Gateway API docs recommend we apply a big bundle of yamls, but we will just curl them and add them to our repository. [6]
curl https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.5.0/experimental-install.yaml > crds.yaml
And then we create the Argo application and manage it through there! For the Envoy Gateway CRDs I did the exact same thing. Found the yaml, placed it on a separate application in my repo and deployed it.
Don't forget to set ServerSideApply=true on both of your CRD Argo applications!
Now for the actual chart, we dont need to modify the values at all so it really is just a raw deploy. But I did find a hurdle along the way for the OIDC requirement, so I will explain it now. Since the OIDC call out will now be made by envoy gateway, rather than an intermideary party like oauth2. If your OpenID Connect provider has a non-publicly trusted certificate, we will need to add it to the trusted certs for our envoy gateway deployment. And to make this modification, since the chart is so bare bones and there is no templating for this. We need to use Kustomize! Add that to the list of technologies I randomly learn about when developing my lab :)
With Kustomize you can apply a helm chart and then implement a patch to tweak the final K8s resource we desire. But to do this with Argo, you must allow Kustomize to deploy Helm charts, so add to your argocd configmap:
apiVersion: v1
kind: ConfigMap
metadata:
name: argocd-cm
data:
kustomize.buildOptions: "--enable-helm"
...
And restart the ArgoCD repo server.
# patches/ca.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: envoy-gateway
spec:
template:
spec:
containers:
- name: envoy-gateway
volumeMounts:
- name: homelab-ca
mountPath: /etc/ssl/certs/homelab-ca.crt
subPath: ca.crt
readOnly: true
volumes:
- name: homelab-ca
configMap:
name: homelab-ca-bundle
items:
- key: ca.crt
path: ca.crt
And to apply this, I had to deploy yet another new application called trust-manager. Which is a part of the cert-manager suite and allows you to create bundle CRDs to place your CA's certificate into namespaces as a configMap. All this, while managing certificate rotation for your authority. [7]
# templates/bundle.yaml
apiVersion: trust.cert-manager.io/v1alpha1
kind: Bundle
metadata:
name: homelab-ca-bundle
spec:
sources:
- secret:
name: ca # the Secret holding your CA cert in cert-manager's namespace
key: ca.crt
target:
configMap:
key: ca.crt
namespaceSelector:
matchExpressions:
- key: kubernetes.io/metadata.name
operator: In
values:
- envoy-gateway-system
Now, if this does not apply to your requirements. Just glance at the values for the envoy chart and deploy it. Easy peasy.
Deployment
Lets deploy our first Gateway then! The process of deploying a Gateway undergoes:
- Defining the Gateway Class for Envoy Gateway
- Defining the Envoy Proxy CRD
- Defining the Gateway itself
We will do like with any other inteface in Kubernetes like CNIs and CSIs, and describe a class for it.
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
name: eg
spec:
controllerName: gateway.envoyproxy.io/gatewayclass-controller
Now, we will define the Envoy Proxy CRD, which deploys the infrastructure our Gateway will use:
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyProxy
metadata:
name: dataplane
namespace: envoy-gateway-system
spec:
provider:
type: Kubernetes
kubernetes:
envoyService:
type: LoadBalancer
externalTrafficPolicy: Cluster
annotations:
metallb.universe.tf/loadBalancerIPs: <free_ip_from_metal_lb_pool>
replicas: 1
The annotation in here is not fully needed. Just helps specify the IP from your pool you want to take.
This is a CRD that wraps around a full Envoy Proxy deployment. It will deploy a service, which if you want to be external from the K8s Network. It should be a Load Balancer as with Ingress. And a deployment for your Envoy Proxy application which will actually route traffic.
The last step is creating the Gateway, which will be the actual configuration your envoy proxy follows. The Envoy Gateway controller watches this object and translates it into Kuberentes enabled Envoy Proxy configurations:
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: dataplane-gateway
spec:
gatewayClassName: eg # Let the controller know that it should handle this gateway.
infrastructure:
# Reference your Envoy Proxy created above
parametersRef:
group: gateway.envoyproxy.io
kind: EnvoyProxy
name: dataplane
namespace: envoy-gateway-system
listeners: # Can remove this until we start migrating from ingress
...
We create listeners once we have routes to migrate to Gateway API, but that's how you create your first Gateway using Envoy Gateway!
Creating HTTP routes with TLS termination
Lets migrate our first basic HTTP Route and explain the listeners key. Migrating from ingress the listener key seems a bit redundant, provided ingress didn't need to modify anything in the controller resource to create a route. But Gateway API gives you more control, what was previously a restriction of Ingress is now stated within the listeners key. This especially allows port and protocol. Lets take a look at a wildcard listener with TLS termination at the Gateway level, which will listen for routes in any namespace.
...
listeners:
- name: tls-termination-https
protocol: HTTPS
port: 443
hostname: "*.yourdomain.com"
tls:
mode: Terminate
certificateRefs:
- name: cert-wildcard
allowedRoutes:
namespaces:
from: All
Here we define a listener that allows any HTTPRoute from any namespace, which will terminate TLS with the same wildcard cert and perform SNI routing. This is a very broad and a little insecure listener. But simplifies developement and effectively "acts" the same way as ingress. The moment any HTTPRoute object is created, for its hostname, Envoy will route the traffic to it. If you do not want wildcard certificates, you can build a list of certificateRefs and Envoy will match the CN of the certificate with the CN of the listener and traffic. Now let's take a look at a more strict listener, which is my preferred choice:
...
...
listeners:
- name: cool-app-https
protocol: HTTPS
port: 443
hostname: "coolapp.yourdomain.com"
tls:
mode: Terminate
certificateRefs:
- name: cert-cool-app
allowedRoutes:
namespaces:
from: Selector
selector:
matchLabels:
kubernetes.io/metadata.name: cool-app-ns
As you can see, this is a single listener for one http route. And I honestly prefer this. If we are going to be modifying the gateway everytime we need it to perform TLS termination, we might as well tighten it. This listener works for one app, one namespace and one certificate. Completely eliminating the chance of undesired or rogue routes popping up.
Now that we are happy with our listener, we need to actually create the route object.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: cool-app
namespace: cool-app-ns
spec:
# Reference the listener above
parentRefs:
- name: dataplane-gateway
namespace: envoy-gateway-system
sectionName: cool-app-https
hostnames:
- coolapp.yourdomain.com
rules:
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: cool-app
port: 80
Quick gotcha. If you notice, the certificate now has moved from the app's namespace to Envoy's. Migrate certificates accordingly.
This is where the actual routing from Envoy Proxy to service happens. And at a glance, looks exactly the same as an Ingress object, just way more verbose. And you are right, for the basic first migration to Gateway API. But the whole idea is agnosticity. Different Ingress Controllers across K8s did not have a very standard look. These objects are a conglomeration of all the benefits each Ingress brought. For example, we can have multiple gateways point to the same route. Allowing different WAF rules to be applied based on the network segment the request is coming from. Something that with vanilla Ingress, was practically impossible.
OpenID Connect integration
Please, read the segment above with Kustomize modifications for Envoy Gateway's helm chart before starting this.
Okay, now that we have the "basics" down, lets reap on the benefits of Gateway API. All compliant Gateway API integrations are able to perform OIDC authentication. No more Oauth2 deployments! So let's follow the Envoy Gateway guide [8]. There are two points where to apply OIDC, at the Gateway or at the HTTPRoute. The biggest difference is whether you want your client to be centralized or have a client per route. For security or obscurity or architecture, I thought that a client per route was the cleanest. So that will be the way I will show it.
To let the route know we need OIDC authentication, we do not need to modify the route itself. Rather, we need to append a SecurityPolicy CRD that will point to our HTTPRoute which will be evaluated before the route's completion. Something very important to keep in mind here is your OIDC provider, in my case, it is an in cluster Keycloak instance. I cannot guarantee that it will look the same for you but it will definetly be very similar given Gateway API's architecture.
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: SecurityPolicy
metadata:
name: cool-app-oidc
namespace: cool-app-ns
spec:
## Reference your HTTPRoute in the same NS.
targetRefs:
- group: gateway.networking.k8s.io
kind: HTTPRoute
name: cool-app
oidc:
provider:
issuer: https://keycloak-endpoint/auth/realms/your-realm
backendRefs:
- name: keycloak-keycloakx-http
namespace: keycloak-ns
port: 80
clientID: cool-app-oidc-client
clientSecret:
name: cool-app-oidc-secret
redirectURL: https://coolapp.yourdomain.com/oauth2/callback
logoutPath: /oauth2/logout
scopes: [openid, email, profile]
# I have found these parameters are appropiate for refreshing OIDC on cookie expiration
refreshToken: true
cookieConfig:
sameSite: Lax
As you may have seen, there are a couple more things to be aware of here. As my keycloak is in the same cluster, my backendRefs points to the Keycloak pod itself. Meaning I need to let the SecurityPolicy in this namespace be able to call it out. So we must have a ReferenceGrant in the Keycloak namespace.
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata:
name: allow-oidc
namespace: keycloak-ns
spec:
from:
- group: gateway.envoyproxy.io
kind: SecurityPolicy
namespace: cool-app-ns
...
to:
- group: ""
kind: Service
If your Keycloak instance is off-cluster then this will not be needed. Your BackendRefs will look a bit different. Probably point to an external service that is allowed to hit that endpoint in-cluster.
Finally, we will need to create a secret for the client to authenticate with Keycloak.
apiVersion: v1
kind: Secret
metadata:
name: cool-app-oidc-secret
namespace: cool-app-ns
type: Opaque
stringData:
client-secret: IAMACOOLSECRETTHATYOUWILLNOTKNOWABOUTBECAUSEIMSECRET
This secret is auto-generated by Keycloak on client creation and it must match. Honestly, compared to what I had with NGINX Ingress. It already is much simpler. No extra Oauth2 deployment and no annotation based authentication. I also had only one client per application in Keycloak so there was no way to track and monitor user authentication on each application.
Mutual TLS Client Authentication from Gateway API
I have a few services in their own hardware like 3D printers listening locally. All of these services lack authentication and some lack even TLS. I route them through my Gateway to get the benefits of OIDC or terminate TLS with the client. In this case I will show LlamaCPP which lacks OIDC and TLS. For TLS it's just about having an NGINX instance running on the Llama host and performing TLS termination there. While the internal applications talk through the localhost interface. But for adding OIDC, I perform a Mutual TLS handshake beteween NGINX and my Envoy Gateway to ensure that all traffic goes through Envoy. We will skip the NGINX semantics here, rather just explain how to present a client certificate with Envoy Gateway to downstreams that require it.
First things first, the client certificate is set at the gateway level. This doesn't harm other routes that don't require it. Because if a server is not listening with mTLS the client simply never presents it.
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyProxy
metadata:
name: dataplane-gateway
namespace: envoy-gateway-system
spec:
...
backendTLS:
## For me it is a cert-manager certificate.
clientCertificateRef:
kind: Secret
name: envoy-lan-client-cert
group: ""
Now, if our gateway already trusts the authority of the downstream server, this would be it! But in most cases the authority is internal and needs to be splicitly provided for Envoy to trust. So let's add a BackendTLSPolicy to mention the CA certificate that needs to be trusted.
apiVersion: gateway.networking.k8s.io/v1alpha3
kind: BackendTLSPolicy
metadata:
name: llama-external-tls
spec:
targetRefs:
- group: ""
kind: Service
name: external-llama-service
validation:
caCertificateRefs:
- kind: ConfigMap
name: homelab-ca-bundle
group: ""
hostname: llama.yourdomain.com
Modify the trust-manager bundle above to deploy this.
And honestly, it felt so much simpler than with NGINX's annotations. That is it! Of course, I didn't go over creating the external service and endpoint slice since they are out of scope for this blog.
TCP Routes
Now we get to the biggest draw with Envoy Gateway. It's flexibility. I have had a dream, since my previous CNPG blog, to have a fleet of dev DBs to develop with. I have one right now, but I already have a couple projects I would like to develop and will require a PSQL instance for.
So let's get to it! I want SNI for port 5432 on Envoy to route my PSQL instances. For this we will create a TLSRoute since PSQL is listening on TLS. This means we will need Envoy Gateway to perform TLS passthrough and... Oh. [9]. Well that is an excuse for another blog. I guess...
It is an open issue on Gateway API's Github repo that mentions a problem with PSQL < 17 STARTTLS and TLS passthrough. Since STARTTLS begins the negotiation in plaintext to request a tunnel. Envoy Gateway gets confused and drops those frames. And I chose PSQL 16 for all my existing instances... Sometimes, you just hit a wall and are unlucky.
Well. Let's do the same thing you can do with NGINX for now. I will forego my SNI routing dream and just use TCPRoutes to proxy the requests to CNPG. And this looks exactly the same as with HTTPRoutes! Just append to your Gateway a TCPRoute listener onto the proper namespace and assign a port. For multiple routes, we can just use different ports. At least until they fix the issue mentioned above or I migrate to Postgres 17.
...
listeners:
...
- name: dev-postgres
protocol: TCP
port: 5432
allowedRoutes:
kinds:
- kind: TCPRoute
namespaces:
from: Selector
selector:
matchLabels:
kubernetes.io/metadata.name: my-app
Then in the app namespace, same as with HTTPRoute, just add the proper CRD and the gateway reference.
apiVersion: gateway.networking.k8s.io/v1alpha2
kind: TCPRoute
metadata:
name: postgres-dev
namespace: my-app
spec:
# Reference the listener above
parentRefs:
- name: dataplane-gateway
namespace: envoy-gateway-system
sectionName: cool-app-https
rules:
- backendRefs:
- name: cnpg-cluster-rw # the read-write Service CNPG creates
port: 5432
And that is A solution. Incredibly underwhelming. Especially given the fact I hyped this SNI solution in my previous blog. But that is the life of a software dev!
Let's not be sad that it didn't happen. Rather enjoy the rabbit hole that it took us under!
Metrics and dashboards
And the last step in the migration is monitoring. I believe that after a long migration, deployment and heart break from issue #4594. A little Arts and Crafts is the best way to slow down the revolutions in our brains. It is also inredibly benefitial and cool. For this Arts and Crafts section I went with only metrics because I did not want to right size with my Loki's limited size. The Envoy Gateway chart automatically listens on it's metrics endpoint. To enable the Prometheus metrics listener on our EnvoyProxy we just have to append this section to the CRD.
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyProxy
metadata:
name: dataplane
namespace: envoy-gateway-system
spec:
...
telemetry:
metrics:
prometheus: {}
Then, it is Arts and Crafts time! I decided to use two well known dashboards to monitor at the Envoy Gateway level and the Proxy/Route level. But there a ton of them. [10], [11] are the 2 raw links from Envoy's Github containing envoy-gateway-global.json and envoy-clusters.json. And after some tweaking, which is always needed with dashboards, they look pretty good!
I hope this has helped you. Maybe you find resources that were elusive or maybe with the migration. I will tackle creating a WAF enabled gateway next. I wll also end up upgrading Postgres to version 17. So keep an eye out for these!
References
- [1] Gateway API
- [2] Ingress NGINX Retirement
- [3] Gateway API Implementations
- [4] CNPG is the only way I can see myself running Postgres
- [5] Installing Envoy Gateway
- [6] Getting started with Gateway API
- [7] Trust-manager documentation
- [8] OIDC Integration
- [9] TLS passthrough Gateway and TLSRoute to SSL-enabled PostgreSQL instance not working #4594
- [10] Envoy Gateway Controller Dashboard
- [11] Envoy Clusters Dashboard