Envoy Gateway is an open source project for managing Envoy Proxy as a standalone or Kubernetes-based application
gateway. Gateway API resources are used to dynamically provision and configure the managed Envoy Proxies.
Project status
Envoy Gateway is a sub-project of Envoy, a graduated CNCF project. Where to find the details when you evaluate it:
Releases and support: Envoy Gateway follows semantic versioning and ships a minor release every quarter. A minor release is supported for 6 months, and the maintainers may reassess that as the project matures. Releases has the schedule and end-of-life dates.
What it runs with: the Compatibility Matrix lists the Envoy Proxy, Gateway API and Kubernetes versions each release is tested against.
Who uses it: the organizations that have added themselves as adopters, and the companies that offer enterprise support, are shown on the home page. The Adopters and Enterprise Support pages explain how to be listed.
Coming from NGINX Ingress:Migrating from Ingress Resources describes ingress2eg, an unofficial proof-of-concept tool that converts NGINX annotations to Envoy Gateway resources.
Ready to get started?
1 - Concepts
Learn about key concepts when working with Envoy Gateway
Overview
Envoy Gateway is a Kubernetes-native API Gateway and reverse proxy control plane. It simplifies deploying and operating Envoy Proxy as a data plane by using the standard Gateway API and its own extensible APIs.
By combining Envoy’s performance and flexibility with Kubernetes-native configuration, Envoy Gateway helps platform teams expose and manage secure, observable, and scalable APIs with minimal operational overhead.
Why Use Envoy Gateway?
Traditionally, configuring Envoy Proxy required deep networking expertise and writing complex configuration files. Envoy Gateway removes that barrier by:
Integrating tightly with Kubernetes through the Gateway API
Providing custom CRDs for advanced traffic policies
Automatically translating Kubernetes resources into Envoy config
Managing the lifecycle of Envoy Proxy instances
Envoy Gateway is designed to be simple for app developers, powerful for platform engineers, and production-ready for large-scale deployments.
Structure
The different layers of Envoy Gateway are the following:
Layer
Description
User Configuration
Users define routing, security, and traffic policies using standard Kubernetes Gateway API resources, optionally extended with Envoy Gateway CRDs.
Envoy Gateway Controller
A control plane component that watches Gateway API and Envoy Gateway-specific resources, translates them, and produces configuration for Envoy Proxy.
Envoy Proxy(Data Plane)
A high-performance proxy that receives and handles live traffic according to the configuration generated by Envoy Gateway.
Together, these layers create a system that’s:
Easy to configure
Powerful enough for complex needs
Standardized and familiar
Ready for the future
Reference Architecture
The diagram below shows these layers in a cluster.
Platform and application teams declare the desired state with Gateway API resources and Envoy Gateway policies, for example with kubectl or a GitOps tool.
The Envoy Gateway Controller watches these resources through the Kubernetes API, translates them into Envoy configuration and writes their status back.
By default, Envoy Gateway provisions one Envoy Proxy fleet per Gateway (per GatewayClass when mergeGateways is enabled), with the Service that exposes it, in the Envoy Gateway namespace (envoy-gateway-system by default), or in each Gateway’s namespace with Gateway Namespace Mode. The fleet is a Deployment by default, customizable with the EnvoyProxy resource, and the proxies get their configuration from Envoy Gateway over xDS (gRPC).
Client traffic enters through that Service and is routed by Envoy to the backends selected by the routes. Envoy can also call optional external authorization (ext auth) or external processing (ext proc) services.
When global rate limiting is enabled in the Envoy Gateway configuration, Envoy Gateway also deploys a rate limit service and configures it over xDS; it is backed by a Redis instance that you provide.
For the internal components of the control plane, see the System Design document.
Resources
There are several resources that play a part in enabling you to meet your Kubernetes ingress traffic handling needs. This page provides a brief overview of the resources you’ll be working with.
Kubernetes Gateway API Resources
GatewayClass: Defines a class of Gateways with common configuration.
Gateway: Specifies how traffic can enter the cluster.
Routes:HTTPRoute, GRPCRoute, TLSRoute, TCPRoute, UDPRoute: Define routing rules for different types of traffic.
Envoy Gateway (EG) API Resources
EnvoyProxy: Represents the deployment and configuration of the Envoy proxy within a Kubernetes cluster, managing its lifecycle and settings.
EnvoyPatchPolicy, ClientTrafficPolicy, SecurityPolicy, BackendTrafficPolicy, EnvoyExtensionPolicy, BackendTLSPolicy: Additional policies and configurations specific to Envoy Gateway.
Backend: A resource that makes routing to cluster-external backends easier and makes access to external processes via Unix Domain Sockets possible.
Used for routing to cluster-external backends using FQDN or IP. Can also be used when you want to extend Envoy with external processes accessed via Unix Domain Sockets.
Specifies policies for traffic directed towards backend services, including load balancing, health checks, and failover strategies. Note:Most specific configuration wins
Defines security-related policies such as authentication, authorization, and encryption settings for traffic handled by Envoy Gateway. Note:Most specific configuration wins
Defines TLS settings for backend connections, including certificate management, TLS version settings, and other security configurations. This policy is applied to Kubernetes Services.
The EnvoyProxy resource represents the deployment and configuration of the Envoy proxy itself within a Kubernetes cluster, managing its lifecycle and settings. Note:Most specific configuration wins
This policy defines custom patches to be applied to Envoy Gateway resources, allowing users to tailor the configuration to their specific needs. Note:Most specific configuration wins
The Gateway API is a Kubernetes API designed to provide a consistent, expressive, and extensible method for managing network traffic into and within a Kubernetes cluster, compared to the legacy Ingress API. It introduces core resources such as GatewayClass and Gateway and various route types like HTTPRoute and TLSRoute, which allow you to define how traffic is routed, secured, and exposed.
The Gateway API succeeds the Ingress API, which many Kubernetes users may already be familiar with. The Ingress API provided a mechanism for exposing HTTP(S) services to external traffic. The lack of advanced features like regex path matching led to custom annotations to compensate for these deficiencies. This non-standard approach led to fragmentation across Ingress Controllers, challenging portability.
Use Cases
Use The Gateway API to:
Define how external traffic enters and is routed within your cluster
Configure HTTP(S), TLS, and TCP traffic routing in a standardized, Kubernetes-native way
Apply host-based, path-based, and header-based routing rules using HTTPRoute
Terminate TLS at the edge using Gateway TLS configuration
Separate responsibilities between infrastructure and application teams through role-oriented resource design
Improve portability and consistency across different gateway implementations
The Gateway API in Envoy Gateway
In essence, the Gateway API provides a standard interface. Envoy Gateway adds production-grade capabilities to that interface, bridging the gap between simplicity and power while keeping everything Kubernetes-native.
One of the Gateway API’s key strengths is that implementers can extend it. While providing a foundation for standard routing and traffic control needs, it enables implementations to introduce custom resources that address specific use cases.
Envoy Gateway leverages this model by introducing a suite of Gateway API extensions—implemented as Kubernetes Custom Resource Definitions (CRDs)—to expose powerful features from Envoy Proxy. These features include enhanced support for rate limiting, authentication, traffic shaping, and more. By utilizing these extensions, users can access production-grade functionality in a Kubernetes-native and declarative manner, without needing to write a low-level Envoy configuration.
Gateway API Extensions let you configure extra features that aren’t part of the standard Kubernetes Gateway API. These extensions are built by the teams that create and maintain Gateway API implementations.
The Gateway API was designed to be extensible, safe, and reliable. In the old Ingress API, people had to use custom annotations to add new features, but those weren’t type-safe, making it hard to check if their configuration was correct.
With Gateway API Extensions, implementers provide type-safe Custom Resource Definitions (CRDs). This means every configuration you write has a clear structure and strict rules, making it easier to catch mistakes early and be confident your setup is valid.
Use Cases
Here are some examples of what kind of features extensions include:
Advanced Traffic Management:
Implementing sophisticated load balancing algorithms, circuit breaking, or retries not defined in the core API
Enhanced Security Controls:
Adding implementation-specific TLS configurations, authentication mechanisms, or access control rules
Observability Integration:
Connecting Gateway resources to monitoring systems, logging pipelines, or tracing frameworks
Custom Protocol Support:
Extending beyond HTTP/TCP/UDP with specialized protocol handling
Rate Limiting and Compression:
Implementing traffic policing specific to the implementation’s capabilities
Gateway API Extensions in Envoy Gateway
The Envoy Gateway API introduces a set of Gateway API extensions that enable users to leverage the power of the Envoy proxy. Envoy Gateway uses a policy attachment model, where custom policies are applied to standard Gateway API resources (like HTTPRoute or Gateway) without modifying the core API. This approach provides separation of concerns and makes it easier to manage configurations across teams.
These extensions are processed through Envoy Gateway’s control plane, translating them into xDS configurations applied to Envoy Proxy instances. This layered architecture allows for consistent, scalable, and production-grade traffic control without needing to manage raw Envoy configuration directly.
BackendTrafficPolicy is an extension to the Kubernetes Gateway API that controls how Envoy Gateway communicates with your backend services. It can configure connection behavior, resilience mechanisms, and performance optimizations without requiring changes to your applications.
Think of it as a traffic controller between your gateway and backend services. It can detect problems, prevent failures from spreading, and optimize request handling to improve system stability.
Use Cases
BackendTrafficPolicy is particularly useful in scenarios where you need to:
Protect your services:
Limit connections and reject excess traffic when necessary
Build resilient systems:
Detect failing services and redirect traffic
Improve performance:
Optimize how requests are distributed and responses are handled
Test system behavior:
Inject faults and validate your recovery mechanisms
BackendTrafficPolicy in Envoy Gateway
BackendTrafficPolicy is part of the Envoy Gateway API suite, which extends the Kubernetes Gateway API with additional capabilities. It’s implemented as a Custom Resource Definition (CRD) that you can use to configure how Envoy Gateway manages traffic to your backend services.
Targets
BackendTrafficPolicy can be attached to Gateway API resources using two targeting mechanisms:
Direct Reference (targetRefs): Explicitly reference specific resources by name and kind.
# Direct reference targetingapiVersion:gateway.envoyproxy.io/v1alpha1kind:BackendTrafficPolicymetadata:name:direct-policyspec:targetRefs:- kind:HTTPRoutename:my-routecircuitBreaker:maxConnections:50---# Label-based targetingapiVersion:gateway.envoyproxy.io/v1alpha1kind:BackendTrafficPolicymetadata:name:selector-policyspec:targetSelectors:- kind:HTTPRoutematchLabels:app:payment-servicerateLimit:local:requests:10unit:Second
The policy applies to all resources that match either targeting method. You can target various Gateway API resource types including
Gateway, ListenerSet, HTTPRoute, GRPCRoute, TCPRoute, UDPRoute, TLSRoute.
When a BackendTrafficPolicy targets a ListenerSet, it applies only to listeners in that ListenerSet. It does not apply to listeners owned directly by the parent Gateway. A ListenerSet target can also use sectionName to apply the policy to a single listener in the ListenerSet.
Route-level policies apply to the targeted route regardless of whether that route is attached directly to a Gateway or through a ListenerSet.
Important: A BackendTrafficPolicy can only target resources in the same namespace as the policy itself.
Precedence
When multiple BackendTrafficPolicies apply to the same resource, Envoy Gateway resolves conflicts using a precedence hierarchy based on the target resource type, route attachment path, and section-level specificity.
Route-specific policies take precedence first:
Route rule-level policies (HTTPRoute/GRPCRoute with sectionName targeting specific rules)
Route-level policies (HTTPRoute, GRPCRoute without sectionName)
After route-specific policies, parent policy precedence depends on how the route is attached.
For routes attached through a ListenerSet:
ListenerSet listener-level policies (ListenerSet with sectionName targeting a specific ListenerSet listener)
ListenerSet-level policies (ListenerSet without sectionName)
Gateway-level policies (Gateway without sectionName) on the parent Gateway
For routes attached directly to a Gateway:
Gateway listener-level policies (Gateway with sectionName targeting specific Gateway-owned listeners)
Gateway-level policies (Gateway without sectionName)
Gateway listener-level policies are sibling scopes to ListenerSet listeners and do not apply to routes attached through a ListenerSet.
# Gateway-level policy (lower precedence) - Applies to all routes in the gatewayapiVersion:gateway.envoyproxy.io/v1alpha1kind:BackendTrafficPolicymetadata:name:gateway-policyspec:targetRefs:- kind:Gatewayname:my-gatewaycircuitBreaker:maxConnections:100---# Route-level policy (higher precedence)apiVersion:gateway.envoyproxy.io/v1alpha1kind:BackendTrafficPolicymetadata:name:route-policyspec:targetRefs:- kind:HTTPRoutename:my-routecircuitBreaker:maxConnections:50
In this example, the HTTPRoute my-route would use maxConnections: 50 from the route-level policy, overriding the gateway-level setting of 100.
Multiple Policies at the Same Level
When multiple BackendTrafficPolicies target the same resource at the same hierarchy level (e.g., multiple policies targeting the same HTTPRoute), Envoy Gateway uses the following tie-breaking rules:
Creation Time Priority: The oldest policy (earliest creationTimestamp) takes precedence
Name-based Sorting: If policies have identical creation timestamps, they are sorted alphabetically by namespaced name, with the first policy taking precedence
# Policy created first - takes precedenceapiVersion:gateway.envoyproxy.io/v1alpha1kind:BackendTrafficPolicymetadata:name:alpha-policycreationTimestamp:"2023-01-01T10:00:00Z"spec:targetRefs:- kind:HTTPRoutename:my-routecircuitBreaker:maxConnections:30---# Policy created later - lower precedenceapiVersion:gateway.envoyproxy.io/v1alpha1kind:BackendTrafficPolicymetadata:name:beta-policycreationTimestamp:"2023-01-01T11:00:00Z"spec:targetRefs:- kind:HTTPRoutename:my-routecircuitBreaker:maxConnections:40
In this example, alpha-policy would take precedence due to its earlier creation time, so the HTTPRoute would use maxConnections: 30.
When the mergeType field is unset, no merging occurs and only the most specific configuration takes effect. However, policies can be configured to merge with parent policies using the mergeType field (see Policy Merging section below).
Policy Merging
BackendTrafficPolicy supports merging configurations using the mergeType field, which allows route-level or route rule-level policies to combine with parent policies rather than completely overriding them. This enables layered policy strategies where platform teams can set baseline configurations at the Gateway or ListenerSet level, while application teams can add specific policies for their routes.
When merging occurs, route-level policies merge with the closest parent policy in the route’s attachment hierarchy:
For routes attached directly to a Gateway, the route policy first looks for a Gateway listener-level policy, then a Gateway-level policy.
For routes attached through a ListenerSet, the route policy first looks for a ListenerSet listener-level policy, then a ListenerSet-level policy, then the parent Gateway-level policy.
A route policy attached through a ListenerSet does not merge with a Gateway listener-level policy because Gateway listeners and ListenerSet listeners are sibling scopes.
Merge Types
StrategicMerge: Uses Kubernetes strategic merge patch semantics, providing intelligent merging for complex data structures including arrays
JSONMerge: Uses RFC 7396 JSON Merge Patch semantics, with simple replacement strategy where arrays are completely replaced
Example Usage
Here’s an example demonstrating policy merging for rate limiting:
# Platform team: Gateway-level policy with global abuse preventionapiVersion:gateway.envoyproxy.io/v1alpha1kind:BackendTrafficPolicymetadata:name:global-backendtrafficpolicyspec:rateLimit:global:rules:- clientSelectors:- sourceCIDR:type:Distinctvalue:0.0.0.0/0limit:requests:100unit:Secondshared:truetargetRefs:- group:gateway.networking.k8s.iokind:Gatewayname:eg---# Application team: Route-level policy with specific limitsapiVersion:gateway.envoyproxy.io/v1alpha1kind:BackendTrafficPolicymetadata:name:route-backendtrafficpolicyspec:mergeType:StrategicMerge # Enables merging with gateway policyrateLimit:global:rules:- clientSelectors:- sourceCIDR:type:Distinctvalue:0.0.0.0/0limit:requests:5unit:Minuteshared:falsetargetRefs:- group:gateway.networking.k8s.iokind:HTTPRoutename:signup-service-httproute
In this example, the route-level policy merges with the gateway-level policy, resulting in both rate limits being enforced: the global 100 requests/second abuse limit and the route-specific 5 requests/minute limit.
Key Constraints
The mergeType field can only be set on policies targeting xRoute resources (like HTTPRoute), not parent resources (like Gateway or ListenerSet)
When mergeType is unset, no merging occurs - only the most specific policy takes effect
The merged configuration combines both policies, enabling layered protection strategies
ClientTrafficPolicy is an extension to the Kubernetes Gateway API that allows system administrators to configure how the Envoy Proxy server behaves with downstream clients. It is a policy attachment resource that can be applied to Gateway and ListenerSet resources and holds settings for configuring the behavior of the connection between the downstream client and Envoy Proxy listener.
Think of ClientTrafficPolicy as a set of rules for your Gateway’s entry points, it lets you configure specific behaviors for each listener in your Gateway, with more specific rules taking precedence over general ones.
Use Cases
ClientTrafficPolicy is particularly useful in scenarios where you need to:
Enforce TLS Security
Configure TLS termination, mutual TLS (mTLS), and certificate validation at the edge.
Manage Client Connections
Control TCP keepalive behavior and connection timeouts for optimal resource usage.
Handle Client Identity
Configure trusted proxy chains to correctly resolve client IPs for logging and access control.
Normalize Request Paths
Sanitize incoming request paths to ensure compatibility with backend routing rules.
Tune HTTP Protocols
Configure HTTP/1, HTTP/2, and HTTP/3 settings for compatibility and performance.
Monitor Listener Health
Set up health checks for integration with load balancers and failover mechanisms.
ClientTrafficPolicy in Envoy Gateway
ClientTrafficPolicy is part of the Envoy Gateway API suite, which extends the Kubernetes Gateway API with additional capabilities. It’s implemented as a Custom Resource Definition (CRD) that you can use to configure how Envoy Gateway manages incoming client traffic.
Targets
ClientTrafficPolicy can be attached to Gateway API resources using two targeting mechanisms:
Direct Reference (targetRefs): Explicitly reference specific resources by name and kind. Supported kinds are:
Gateway — apply the policy to all listeners on the Gateway (or a specific listener via sectionName)
ListenerSet — apply the policy to all listeners in the ListenerSet (or a specific listener via sectionName)
Label Selection (targetSelectors): Match resources based on their labels (see targetSelectors API reference). Both Gateway and ListenerSet kinds are supported.
The policy applies to all resources that match either targeting method.
Targeting a ListenerSet is useful when you want to apply client traffic settings to a group of listeners managed independently from the parent Gateway, without affecting Gateway-owned listeners.
Important: A ClientTrafficPolicy can only target resources in the same namespace as the policy itself.
Precedence
When multiple ClientTrafficPolicies apply to the same listener, Envoy Gateway resolves conflicts using target specificity and creation-time priority:
Section-specific policies (targeting a specific listener via sectionName on a Gateway or ListenerSet) - Highest precedence
ListenerSet-wide policies (targeting an entire ListenerSet) - Medium precedence
Gateway-wide policies (targeting an entire Gateway) - Lowest precedence
A ListenerSet-wide policy takes precedence over a Gateway-wide policy for any listener that belongs to that ListenerSet. The Gateway-wide policy is still applied to listeners that are owned directly by the Gateway and not covered by a ListenerSet-wide policy.
Multiple Policies at the Same Level
When multiple ClientTrafficPolicies target the same resource at the same specificity level (e.g., multiple policies targeting the same Gateway listener section), Envoy Gateway uses the following tie-breaking rules:
Creation Time Priority: The oldest policy (earliest creationTimestamp) takes precedence
Name-based Sorting: If policies have identical creation timestamps, they are sorted alphabetically by namespaced name, with the first policy taking precedence
# Policy created first - takes precedenceapiVersion:gateway.envoyproxy.io/v1alpha1kind:ClientTrafficPolicymetadata:name:alpha-policycreationTimestamp:"2023-01-01T10:00:00Z"spec:targetRefs:- kind:Gatewayname:my-gatewaysectionName:https-listenertimeout:http:idleTimeout:30s---# Policy created later - lower precedenceapiVersion:gateway.envoyproxy.io/v1alpha1kind:ClientTrafficPolicymetadata:name:beta-policycreationTimestamp:"2023-01-01T11:00:00Z"spec:targetRefs:- kind:Gatewayname:my-gatewaysectionName:https-listenertimeout:http:idleTimeout:40s
In this example, alpha-policy would take precedence due to its earlier creation time, so the listener would use idleTimeout: 30s.
For example, consider these policies with different specificity levels targeting the same Gateway:
# Policy A: Targets a specific listener in the gatewayapiVersion:gateway.envoyproxy.io/v1alpha1kind:ClientTrafficPolicymetadata:name:listener-specific-policyspec:targetRefs:- kind:Gatewayname:my-gatewaysectionName:https-listener # Targets specific listenertimeout:http:idleTimeout:30s---# Policy B: Targets the entire gatewayapiVersion:gateway.envoyproxy.io/v1alpha1kind:ClientTrafficPolicymetadata:name:gateway-wide-policyspec:targetRefs:- kind:Gatewayname:my-gateway # Targets all listenerstimeout:http:idleTimeout:60s
In this case:
Policy A will be applied/attached to the specific Listener defined in the targetRef.SectionName
Policy B will be applied to the remaining Listeners within the Gateway. Policy B will have an additional status condition Overridden=True.
The same specificity rules apply when a ListenerSet is involved. Consider this example where a Gateway and a ListenerSet each have a policy, plus a section-specific policy on the ListenerSet:
# Policy A: Targets a specific listener in a ListenerSet (highest precedence for that listener)apiVersion:gateway.envoyproxy.io/v1alpha1kind:ClientTrafficPolicymetadata:name:listenerset-section-policyspec:targetRefs:- group:gateway.networking.k8s.iokind:ListenerSetname:my-listener-setsectionName:ext-https # Targets a single listenertls:minVersion:"1.3"---# Policy B: Targets the entire ListenerSet (beats Gateway-wide for ListenerSet listeners)apiVersion:gateway.envoyproxy.io/v1alpha1kind:ClientTrafficPolicymetadata:name:listenerset-wide-policyspec:targetRefs:- group:gateway.networking.k8s.iokind:ListenerSetname:my-listener-settimeout:http:idleTimeout:45s---# Policy C: Targets the entire Gateway (lowest precedence)apiVersion:gateway.envoyproxy.io/v1alpha1kind:ClientTrafficPolicymetadata:name:gateway-wide-policyspec:targetRefs:- kind:Gatewayname:my-gatewaytimeout:http:idleTimeout:60s
In this case:
Policy A is applied to the ext-https listener in the ListenerSet.
Policy B is applied to the remaining listeners in my-listener-set. Policy B will have Overridden=True for the ext-https listener covered by Policy A.
Policy C is applied to listeners owned directly by my-gateway that are not part of my-listener-set. Policy C will have Overridden=True for every listener covered by Policy A or Policy B.
When a ClientTrafficPolicy targets a ListenerSet, the policy’s status ancestorRef is set to the ListenerSet itself rather than the parent Gateway, so you can observe attachment status scoped to the ListenerSet directly.
SecurityPolicy is an Envoy Gateway extension to the Kubernetes Gateway API that allows you to define authentication and authorization requirements for traffic entering your gateway. It acts as a security layer that only properly authenticated and authorized requests are allowed through your backend services.
SecurityPolicy is designed for you to enforce access controls through configuration at the edge of your infrastructure in a declarative, Kubernetes-native way, without needing to configure complex proxy rules manually.
Use Cases
Authentication Methods:
Authenticate client apps using mTLS, JWTs, API keys, or Basic Auth
Authenticate users with OIDC Provider integration
Authorization Controls:
Define and enforce authorization rules based on user roles and permissions
Integrate with external authorization services for real-time policy decisions
JWT Token Authorization Checks
Cross-Origin Security:
Configure CORS to allow or restrict cross-origin requests for APIs
SecurityPolicy in Envoy Gateway
SecurityPolicy is implemented as a Kubernetes Custom Resource Definition (CRD) and follows the policy attachment model.
Targets
SecurityPolicy can be attached to Gateway API resources using two targeting mechanisms:
Direct Reference (targetRefs): Explicitly reference specific resources by name and kind.
The policy applies to all resources that match either targeting method. You can target various Gateway API resource types including Gateway, ListenerSet, HTTPRoute, GRPCRoute, TCPRoute, and UDPRoute.
When a SecurityPolicy targets a ListenerSet, it applies only to listeners in that ListenerSet. It does not apply to listeners owned directly by the parent Gateway. A ListenerSet target can also use sectionName to apply the policy to a single listener in the ListenerSet.
Route-level policies apply to the targeted route regardless of whether that route is attached directly to a Gateway or through a ListenerSet.
Note: TCPRoute and UDPRoute support is limited to authorization using client IP allow/deny lists (IP-based authorization). Other SecurityPolicy features such as JWT, API Key, Basic Auth, or OIDC are not applicable to L4 targets, since there is no HTTP request to inspect. For a UDPRoute the client IP is the source address of the datagram, and a denied source is dropped without a reply.
Important: A SecurityPolicy can only target resources in the same namespace as the policy itself.
Precedence
When multiple SecurityPolicies apply to the same resource, Envoy Gateway resolves conflicts using a precedence hierarchy based on the target resource type, route attachment path, and section-level specificity.
Route-specific policies take precedence first:
Route rule-level policies (HTTPRoute, GRPCRoute, TCPRoute, or UDPRoute with sectionName targeting specific rules)
Route-level policies (HTTPRoute, GRPCRoute, TCPRoute, or UDPRoute without sectionName)
After route-specific policies, parent policy precedence depends on how the route is attached.
For routes attached through a ListenerSet:
ListenerSet listener-level policies (ListenerSet with sectionName targeting a specific ListenerSet listener)
ListenerSet-level policies (ListenerSet without sectionName)
Gateway-level policies (Gateway without sectionName) on the parent Gateway
For routes attached directly to a Gateway:
Gateway listener-level policies (Gateway with sectionName targeting specific Gateway-owned listeners)
Gateway-level policies (Gateway without sectionName)
Gateway listener-level policies are sibling scopes to ListenerSet listeners and do not apply to routes attached through a ListenerSet.
Multiple Policies at the Same Level
When multiple SecurityPolicies target the same resource at the same hierarchy level (e.g., multiple policies targeting the same HTTPRoute), Envoy Gateway uses the following tie-breaking rules:
Creation Time Priority: The oldest policy (earliest creationTimestamp) takes precedence
Name-based Sorting: If policies have identical creation timestamps, they are sorted alphabetically by namespaced name, with the first policy taking precedence
# Policy created first - takes precedenceapiVersion:gateway.envoyproxy.io/v1alpha1kind:SecurityPolicymetadata:name:alpha-policycreationTimestamp:"2023-01-01T10:00:00Z"spec:targetRefs:- kind:HTTPRoutename:my-routecors:allowOrigins:- exact:https://example.com---# Policy created later - lower precedenceapiVersion:gateway.envoyproxy.io/v1alpha1kind:SecurityPolicymetadata:name:beta-policycreationTimestamp:"2023-01-01T11:00:00Z"spec:targetRefs:- kind:HTTPRoutename:my-routecors:allowOrigins:- exact:https://different.com
In this example, alpha-policy would take precedence due to its earlier creation time, so the HTTPRoute would use the CORS setting from alpha-policy.
# HTTPRoute with named rulesapiVersion:gateway.networking.k8s.io/v1kind:HTTPRoutemetadata:name:my-routespec:rules:- name:rule-1 # Named rule for sectionName targetingmatches:- path:value:"/api"backendRefs:- name:api-serviceport:80---# Route rule-level policy (highest precedence)apiVersion:gateway.envoyproxy.io/v1alpha1kind:SecurityPolicymetadata:name:rule-policyspec:targetRefs:- kind:HTTPRoutename:my-routesectionName:rule-1 # Targets specific named rulecors:allowOrigins:- exact:https://rule.example.com---# Route-level policy (high precedence)apiVersion:gateway.envoyproxy.io/v1alpha1kind:SecurityPolicymetadata:name:route-policyspec:targetRefs:- kind:HTTPRoutename:my-route # No sectionName = entire routecors:allowOrigins:- exact:https://route.example.com---# Listener-level policy (medium precedence)apiVersion:gateway.envoyproxy.io/v1alpha1kind:SecurityPolicymetadata:name:listener-policyspec:targetRefs:- kind:Gatewayname:my-gatewaysectionName:https-listener # Targets specific listenercors:allowOrigins:- exact:https://listener.example.com---# Gateway-level policy (lowest precedence)apiVersion:gateway.envoyproxy.io/v1alpha1kind:SecurityPolicymetadata:name:gateway-policyspec:targetRefs:- kind:Gatewayname:my-gateway # No sectionName = entire gatewaycors:allowOrigins:- exact:https://gateway.example.com
In this example, the specific rule rule-1 within HTTPRoute my-route would use the CORS settings from the route rule-level policy (https://rule.example.com), overriding the route-level, listener-level, and gateway-level settings.
For section-specific targeting, consider these policies with different hierarchy levels targeting the same Gateway:
# Policy A: Applies to a specific listenerapiVersion:gateway.envoyproxy.io/v1alpha1kind:SecurityPolicymetadata:name:listener-policynamespace:defaultspec:targetRefs:- kind:Gatewayname:my-gatewaysectionName:https # Applies only to "https" listenercors:allowOrigins:- exact:https://example.com---# Policy B: Applies to the entire gatewayapiVersion:gateway.envoyproxy.io/v1alpha1kind:SecurityPolicymetadata:name:gateway-policynamespace:defaultspec:targetRefs:- kind:Gatewayname:my-gateway # Applies to all listenerscors:allowOrigins:- exact:https://default.com
In the example, policy A affects only the HTTPS listener, while policy B applies to the rest of the listeners in the gateway. Since Policy A is more specific, the system will show Overridden=True for Policy B on the https listener.
The same specificity rules apply when a ListenerSet is involved. A section-specific ListenerSet policy applies only to the named ListenerSet listener, while a ListenerSet-wide policy applies to the remaining listeners in that ListenerSet. The parent Gateway-wide policy applies to Gateway-owned listeners and to ListenerSet listeners that do not have a more specific ListenerSet policy. A Gateway listener policy applies only to the listener owned directly by the Gateway and does not affect ListenerSet listeners.
When the mergeType field is unset, no merging occurs and only the most specific configuration takes effect. However, policies can be configured to merge with parent policies using the mergeType field (see Policy Merging section below).
Policy Merging
SecurityPolicy supports merging configurations using the mergeType field, which allows route-level or route rule-level policies to combine with parent policies rather than completely overriding them. This enables layered security strategies where platform teams can set baseline security configurations at the Gateway or ListenerSet level, while application teams can add specific security policies for their routes.
When merging occurs, route-level policies merge with the closest parent policy in the route’s attachment hierarchy:
For routes attached directly to a Gateway, the route policy first looks for a Gateway listener-level policy, then a Gateway-level policy.
For routes attached through a ListenerSet, the route policy first looks for a ListenerSet listener-level policy, then a ListenerSet-level policy, then the parent Gateway-level policy.
A route policy attached through a ListenerSet does not merge with a Gateway listener-level policy because Gateway listeners and ListenerSet listeners are sibling scopes.
Merge Types
StrategicMerge: Uses Kubernetes strategic merge patch semantics, providing intelligent merging for complex data structures including arrays
JSONMerge: Uses RFC 7396 JSON Merge Patch semantics, with simple replacement strategy where arrays are completely replaced
Example Usage
Here’s an example demonstrating policy merging for combining authentication and CORS policies:
# Platform team: Gateway-level policy with baseline authenticationapiVersion:gateway.envoyproxy.io/v1alpha1kind:SecurityPolicymetadata:name:gateway-securitynamespace:defaultspec:targetRefs:- group:gateway.networking.k8s.iokind:Gatewayname:my-gatewaysectionName:https-listenerbasicAuth:users:name:basic-auth-secret---# Application team: Route-level policy with CORS configurationapiVersion:gateway.envoyproxy.io/v1alpha1kind:SecurityPolicymetadata:name:route-securitynamespace:defaultspec:mergeType:StrategicMerge # Enables merging with gateway policytargetRefs:- group:gateway.networking.k8s.iokind:HTTPRoutename:my-routecors:allowOrigins:- exact:https://example.comallowMethods:- GET- POSTallowHeaders:- x-header-1
In this example, the route-level policy merges with the gateway-level policy, resulting in both security controls being enforced: the baseline BasicAuth (from Gateway) and the route-specific CORS policy (from Route). This allows platform teams to enforce organization-wide authentication requirements while enabling application teams to configure route-specific cross-origin policies.
Key Constraints
The mergeType field can only be set on policies targeting child resources (like HTTPRoute), not parent resources (like Gateway or ListenerSet)
When mergeType is unset, no merging occurs - only the most specific policy takes effect
The merged configuration combines both policies, enabling layered security strategies
When the same security feature is configured in both parent and child policies (e.g., both define CORS), the child policy’s configuration takes precedence for that specific feature
Secret references and backend references are resolved against the namespace of the policy that originally configured the field (either route or parent). For example, if a Gateway policy defines BasicAuth, its secret is looked up in the Gateway policy’s namespace even after merging.
An API gateway is a centralized entry point for managing, securing, and routing requests to backend services. It handles cross-cutting concerns, like authentication, rate limiting, and protocol translation, so individual services don’t have to. Decoupling clients from internal systems simplifies scaling, enforces consistency, and reduces redundancy.
Use Cases
Use an API Gateway to:
Avoid duplicating logic across microservices.
Create a central point of control for access, monitoring, and traffic rules.
Expose internal services to the public internet.
Provide protocol support for HTTP, gRPC, or TLS.
Enforce policies and see traffic metrics at the edge.
API Gateways in relation to Envoy Gateway
Under the hood, Envoy Proxy is a powerful, production-grade proxy that supports many of the capabilities you’d expect from an API Gateway, like traffic routing, retries, TLS termination, observability, and more. However, configuring Envoy directly can be complex and verbose.
Envoy Gateway makes configuring Envoy Proxy simple by implementing and extending the Kubernetes-native Gateway API. You define high-level traffic rules using resources like Gateway, HTTPRoute, or TLSRoute, and Envoy Gateway automatically translates them into detailed Envoy Proxy configurations.
A proxy server is an intermediary between a client (like a web browser) and another server (like an API server). When the client makes a request, the proxy forwards it to the destination server, receives the response, and then sends it back to the client.
Proxies are used to enhance security, manage traffic, anonymize user activity, or optimize performance through caching and load balancing features. In cloud environments, they often handle critical tasks such as request routing, TLS termination, authentication, and traffic shaping.
Use Cases
Use Envoy Proxy to:
Manage internal or external traffic with a powerful L3/L4/L7 proxy
Control HTTP, gRPC, or TLS routing with fine-grained match and rewrite rules
Gain full observability via built-in metrics, tracing, and logging
Implement intelligent load balancing and resilient failover strategies
Integrate seamlessly with service meshes, API gateways, and other control planes
Proxy in Envoy Gateway
Envoy Gateway is a system made up of two main parts:
A data plane, which handles the actual network traffic
A control plane, which manages and configures the data plane
Envoy Gateway uses the Envoy Proxy, which was originally developed at Lyft. This proxy is the foundation of the Envoy project, of which Envoy Gateway is a part, and is now a graduated project within the Cloud Native Computing Foundation (CNCF).
Envoy Proxy is a high-performance, open-source proxy designed for cloud-native applications. Envoy supports use cases for edge and service proxies, routing traffic at the system’s boundary or between internal services.
The control plane uses the Kubernetes Gateway API to understand your settings and then translates them into the format Envoy Proxy needs (called xDS configuration). It also runs and updates the Envoy Proxy instances inside your Kubernetes cluster.
As mentioned in the system design document, Envoy Gateway’s managed data plane is configured dynamically through
Kubernetes resources, primarily Gateway API objects. Envoy Gateway supports configuration using the following Gateway API resources.
GatewayClass
A GatewayClass represents a “class” of gateways, i.e. which Gateways should be managed by Envoy Gateway.
Envoy Gateway supports managing a single GatewayClass resource that matches its configured controllerName and
follows Gateway API guidelines for resolving conflicts when multiple GatewayClasses exist with a matching
controllerName.
When a Gateway resource is created that references the managed GatewayClass, Envoy Gateway will create and manage a
new Envoy Proxy deployment. Gateway API resources that reference this Gateway will configure this managed Envoy Proxy
deployment.
HTTPRoute
A HTTPRoute configures routing of HTTP traffic through one or more Gateways. The following HTTPRoute filters are
supported by Envoy Gateway:
requestHeaderModifier: RequestHeaderModifiers
can be used to modify or add request headers before the request is proxied to its destination.
responseHeaderModifier: ResponseHeaderModifiers
can be used to modify or add response headers before the response is sent back to the client.
requestMirror: RequestMirrors
configure destinations where the requests should also be mirrored to. Responses to mirrored requests will be ignored.
requestRedirect: RequestRedirects
configure policied for how requests that match the HTTPRoute should be modified and then redirected.
urlRewrite: UrlRewrites
allow for modification of the request’s hostname and path before it is proxied to its destination.
extensionRef: ExtensionRefs are used by Envoy Gateway to implement extended filters. Currently, Envoy Gateway
supports rate limiting and request authentication filters. For more information about these filters, refer to the
rate limiting and request authentication documentation.
Notes:
The only BackendRef kind supported by Envoy Gateway is a Service. Routing traffic to other destinations such
as arbitrary URLs is not possible.
Only requestHeaderModifier and responseHeaderModifier filters are currently supported within HTTPBackendRef.
TCPRoute
A TCPRoute configures routing of raw TCP traffic through one or more Gateways. Traffic can be forwarded to the
desired BackendRefs based on a TCP port number.
Note: A TCPRoute only supports proxying in non-transparent mode, i.e. the backend will see the source IP and port of
the Envoy Proxy instance instead of the client.
UDPRoute
A UDPRoute configures routing of raw UDP traffic through one or more Gateways. Traffic can be forwarded to the
desired BackendRefs based on a UDP port number.
Note: Similar to TCPRoutes, UDPRoutes only support proxying in non-transparent mode i.e. the backend will see the
source IP and port of the Envoy Proxy instance instead of the client.
GRPCRoute
A GRPCRoute configures routing of gRPC requests through one or more Gateways. They offer request matching by
hostname, gRPC service, gRPC method, or HTTP/2 Header. Envoy Gateway supports the following filters on GRPCRoutes to
provide additional traffic processing:
requestHeaderModifier: RequestHeaderModifiers
can be used to modify or add request headers before the request is proxied to its destination.
responseHeaderModifier: ResponseHeaderModifiers
can be used to modify or add response headers before the response is sent back to the client.
requestMirror: RequestMirrors
configure destinations where the requests should also be mirrored to. Responses to mirrored requests will be ignored.
extensionRef: ExtensionRefs can reference an Envoy Gateway HTTPRouteFilter to enable extended behavior for
gRPC traffic. Since gRPC runs over HTTP/2, a GRPCRoute reuses the same HTTPRouteFilter API as HTTPRoute, supporting
URL rewrite (authority/host and regex :path rewrite), direct response, and credential injection. Note the
gRPC-specific semantics: a regex :path rewrite operates on the gRPC path, which has the form
/<package>.<Service>/<Method>, and for a direct response Envoy adds gRPC status trailers so gRPC clients handle the
response correctly.
Notes:
The only BackendRef kind supported by Envoy Gateway is a Service. Routing traffic to other
destinations such as arbitrary URLs is not currently possible.
Only requestHeaderModifier and responseHeaderModifier filters are currently supported within GRPCBackendRef.
TLSRoute
A TLSRoute configures routing of TCP traffic through one or more Gateways. However, unlike TCPRoutes, TLSRoutes
can match against TLS-specific metadata.
ReferenceGrant
A ReferenceGrant is used to allow a resource to reference another resource in a different namespace. Normally an
HTTPRoute created in namespace foo is not allowed to reference a Service in namespace bar. A ReferenceGrant permits
these types of cross-namespace references. Envoy Gateway supports the following ReferenceGrant use-cases:
Allowing an HTTPRoute, GRPCRoute, TLSRoute, UDPRoute, or TCPRoute to reference a Service in a different namespace.
Allowing an HTTPRoute’s requestMirror filter to include a BackendRef that references a Service in a different
namespace.
Allowing a Gateway’s SecretObjectReference to reference a secret in a different namespace.
1.6 - Load Balancing
Overview
Load balancing distributes incoming requests across multiple backend services to improve availability, responsiveness, and scalability. Instead of directing all traffic to a single backend, which can cause slowdowns or outages, load balancing spreads the load across multiple instances, helping your applications stay fast and reliable under pressure.
Use Cases
Use load balancing to:
Handle high traffic by distributing it across multiple service instances
Keep services available even if one or more backends go down
Improve response time by routing to less busy or closer backends
Load Balancing in Envoy Gateway
Envoy Gateway supports several load balancing strategies that determine how traffic is distributed across backend services. These strategies are configured using the BackendTrafficPolicy resource and can be applied to Gateway, HTTPRoute, or GRPCRoute resources either by directly referencing them using the targetRefs field or by dynamically selecting them using the targetSelectors field, which matches resources based on Kubernetes labels.
Supported load balancing types:
Round Robin – Sends requests sequentially to all available backends
Random – Chooses a backend at random to balance load
Least Request – Sends the request to the backend with the fewest active requests (this is the default)
Consistent Hash – Routes requests based on a hash (e.g., client IP or header), which helps keep repeat requests going to the same backend (useful for session affinity)
Backend Utilization – Uses client-observed load reports (e.g., Open Resource Cost Aggregation (ORCA) metrics) to dynamically weight endpoints; if no metrics are available, it behaves similar to even-weight round-robin.
If no load balancing strategy is specified, Envoy Gateway uses Least Request by default.
Example: Round Robin Load Balancing
This example shows how to apply the Round Robin strategy using a BackendTrafficPolicy that targets a specific HTTPRoute:
In this setup, traffic matching /round is distributed evenly across all available backend service instances. For example, if there are four replicas of the backend service, each one should receive roughly 25% of the requests.
Backend Utilization (ORCA)
Backend Utilization load balancing uses Open Resource Cost Application (ORCA) metrics to make load balancing decisions. These metrics are reported by the backend service in response headers or trailers.
ORCA Load Metrics
The backend service (or its sidecar) reports load metrics in response headers or trailers (for streaming requests). ORCA supports multiple formats for these metrics:
JSON: Use the endpoint-load-metrics header with a JSON object.
By default, Envoy forwards the ORCA response headers/trailers from the upstream cluster to the downstream client. This means that if the downstream client is also configured to use client-side weighted round-robin, it will load balance against Envoy based on upstream weights.
To prevent this, Envoy Gateway automatically removes these headers by default when BackendUtilization is enabled. You can change this behavior using the keepResponseHeaders field in backendUtilization.
apiVersion:gateway.envoyproxy.io/v1alpha1kind:BackendTrafficPolicymetadata:name:backend-utilization-policyspec:targetRefs:- group:gateway.networking.k8s.iokind:HTTPRoutename:backend-utilization-routeloadBalancer:type:BackendUtilizationbackendUtilization:keepResponseHeaders:true# Keep headers and forward them to the client
Rate limiting is a technique for controlling the number of incoming requests over a defined period. It can be used to control usage for business purposes, like agreed usage quotas, or to ensure the stability of a system, preventing overload and protecting the system from, e.g., Denial of Service attacks.
Use Cases
Rate limiting is commonly used to:
Prevent Overload: Protect internal systems like databases from excessive traffic.
Enhance Security: Block or limit abusive behavior such as brute-force attempts or DDoS attacks.
Ensure Fair Usage: Enforce quotas and prevent resource hogging by individual clients.
Implement Entitlements: Define API usage limits based on user identity or role.
Rate Limiting in Envoy Gateway
Envoy Gateway supports two types of rate limiting:
Global Rate Limiting: Shared limits across all Envoy instances.
Local Rate Limiting: Independent limits per Envoy instance.
Envoy Gateway supports rate limiting through the BackendTrafficPolicy custom resource. You can define rate-limiting rules and apply them to HTTPRoute, GRPCRoute, or Gateway resources either by directly referencing them with the targetRefs field or by dynamically selecting them using the targetSelectors field, which matches resources based on Kubernetes labels.
Note
Rate limits are applied per route, even if the BackendTrafficPolicy targets a Gateway. For example, if the limit is 100r/s and a Gateway has 3 routes, each route has its own 100r/s bucket.
Global Rate Limiting
Global rate limiting ensures a consistent request limit across the entire Envoy fleet. This is ideal for shared resources or distributed environments where coordinated enforcement is critical.
Global limits are enforced via Envoy’s external Rate Limit Service, which is automatically deployed and managed by the Envoy Gateway system. The Rate Limit Service requires a datastore component (commonly Redis). When a request is received, Envoy sends a descriptor to this external service to determine if the request should be allowed.
This configuration limits all requests across all Envoy instances for the my-api route to 100 requests per minute total. If there are multiple replicas of Envoy, the limit is shared across all of them.
Local Rate Limiting
Local rate limiting applies limits independently within each Envoy Proxy instance. It does not rely on external services, making it lightweight and efficient—especially for blocking abusive traffic early.
Benefits of local limits:
Lightweight and does not require an external rate limit service
Fast enforcement with rate limiting at the edge
Effective as a first line of defense against traffic bursts
This configuration limits traffic to 50 requests per minute per Envoy instance for the my-api route. If there are two Envoy replicas, up to 100 total requests per minute may be allowed (50 per replica).
Combining Global and Local Rate Limiting
Envoy Gateway supports configuring both Global and Local rate limits simultaneously on the same route. This layered approach provides comprehensive protection by combining the benefits of both strategies.
How it works:
When both rate limits are configured:
Local rate limits is evaluated first at each Envoy instance
Global rate limits is then evaluated using the shared rate limit service
A request must pass both checks to be allowed through
Benefits of combined rate limiting:
Local limits provide immediate protection against sudden traffic spikes at each instance without external service calls
This configuration applies both rate limiting strategies to the my-api route:
Local limiting: Each Envoy instance independently allows up to 50 requests per second. If you have 3 Envoy replicas, the theoretical maximum would be 150 requests per second (50 per replica) assuming perfect load distribution.
Global limiting: All requests across all Envoy instances are limited to 100 requests per minute total. This is enforced by the shared rate limit service, ensuring the combined traffic from all replicas never exceeds this limit.
In practice, a request will be rejected if it exceeds either limit. For example:
If one Envoy instance receives 51 requests in a second, the 51st request is rejected locally (local limit exceeded)
If the system has already processed 100 requests in the current minute across all instances, the 101st request is rejected globally (global limit exceeded)
Note: In case your Kubernetes cluster does not have a LoadBalancer implementation, we recommend installing one
so the Gateway resource has an Address associated with it. We recommend using MetalLB.
Installation
Install the Gateway API CRDs and Envoy Gateway:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the
cluster, use the provider-managed Gateway API CRD install steps
instead.
Note: quickstart.yaml defines that Envoy Gateway will listen for
traffic on port 80 on its globally-routable IP address, to make it easy to use
browsers to test Envoy Gateway. When Envoy Gateway sees that its Listener is
using a privileged port (<1024), it will map this internally to an
unprivileged port, so that Envoy Gateway doesn’t need additional privileges.
It’s important to be aware of this mapping, since you may need to take it into
consideration when debugging.
Testing the Configuration
You can also test the same functionality by sending traffic to the External IP. To get the external IP of the
Envoy service, run:
exportGATEWAY_HOST=$(kubectl get gateway/eg -o jsonpath='{.status.addresses[0].value}')
In certain environments, the load balancer may be exposed using a hostname, instead of an IP address. If so, replace
ip in the above command with hostname.
Review the Tasks section for the scenario matching your use case. The Envoy Gateway tasks are organized by category: traffic management, security, extensibility, observability, and operations.
Clean-Up
Use the steps in this section to uninstall everything from the quickstart.
Envoy Gateway supports routing to native K8s resources such as Service and ServiceImport. The Backend API is a custom Envoy Gateway extension resource that can used in Gateway-API BackendObjectReference.
Motivation
The Backend API was added to support several use cases:
Allowing users to integrate Envoy with services (Ext Auth, Rate Limit, ALS, …) using Unix Domain Sockets, which are currently not supported by K8s.
Similar to the K8s EndpointSlice API, the Backend API can be misused to allow traffic to be sent to otherwise restricted destinations, as described in CVE-2021-25740.
A Backend resource can be used to:
Expose a Service or Pod that should not be accessible
Reference a Service or Pod by a Route without appropriate Reference Grants
Expose the Envoy Proxy localhost (including the Envoy admin endpoint)
When configured as the DynamicResolver type, it can route traffic to any destination, effectively exposing all potential endpoints to clients. This can introduce security risks if not properly managed.
For these reasons, the Backend API is disabled by default in Envoy Gateway configuration. Envoy Gateway admins are advised to follow upstream recommendations and restrict access to the Backend API using K8s RBAC.
Restrictions
The Backend API is currently supported only in the following BackendReferences:
HTTPRoute: IP and FQDN endpoints, and a Kubernetes Service in the same namespace (type: KubernetesService)
Certain restrictions apply on the value of hostnames and addresses. For example, the loopback IP address range and the localhost hostname are forbidden.
Envoy Gateway does not manage the lifecycle of unix domain sockets referenced by the Backend resource. Envoy Gateway admins are responsible for creating and mounting the sockets into the envoy proxy pod. The latter can be achieved by patching the envoy deployment using the EnvoyProxy resource.
Envoy Gateway does not resolve DNS for FQDN endpoints and defers this responsibility to Envoy. When targeting a Kubernetes Service using a FQDN endpoint, Envoy will not consider Kubernetes Endpoint information (such as zone, draining status, specific pod IP).
As a result, features like load balancing, session persistence, draining and zone aware routing may not work as expected. When targeting a Kubernetes Service, consider using the KubernetesService endpoint type.
Kubernetes Service Backends
A Backend with type: KubernetesService points at a Service in the same namespace. Envoy Gateway discovers the endpoints from the Service’s EndpointSlices, the same way it does for a Service backendRef, so pod-level load balancing, session persistence, health checking, endpoint draining and zone-aware routing still apply. Backend settings such as tls and appProtocols are layered on top.
The appProtocols on the Backend take precedence over the appProtocol of the Service port. The endpoints field must not be set for this type.
Quickstart
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Enable Backend
By default Backend is disabled. Lets enable it in the EnvoyGateway startup configuration
The default installation of Envoy Gateway installs a default EnvoyGateway configuration and attaches it
using a ConfigMap. In the next step, we will update this resource to enable Backend.
After updating the ConfigMap, you will need to wait the configuration kicks in. You can force the configuration to be reloaded by restarting the envoy-gateway deployment.
Envoy Gateway can be configured as a dynamic forward proxy using the Backend API by setting its type to DynamicResolver.
This allows Envoy Gateway to act as an HTTP proxy without needing prior knowledge of destination hostnames or IP addresses,
while still maintaining its advanced routing and traffic management capabilities.
Under the hood, Envoy Gateway uses the Envoy Dynamic Forward Proxy
to implement this feature.
In the following example, we will create a HTTPRoute that references a Backend resource of type DynamicResolver.
This setup allows Envoy Gateway to dynamically resolve the hostname in the request and forward the traffic to the original
destination of the request.
Forwarding Based on the Original Host
Note: the TLS configuration in the following example is optional. It’s only required if you want to use TLS to connect
to the backend service. The example uses the system well-known CA certificate to validate the backend service’s certificate.
You can also use a custom CA certificate by specifying the caCertificate field in the tls section.
You can rewrite the host using a request header while still relying on the DynamicResolver backend to resolve that host.
Loopback hostnames/addresses (for example localhost, 127.0.0.1, ::1) are denied by default so rewritten hosts cannot
route to the proxy’s own loopback interface. Add explicit allow/deny rules for other destinations with SecurityPolicy
authorization when you want tighter controls.
Example: rewrite from a custom header and deny rewrites to forbidden.com.
A DynamicResolverBackend can also be referenced by a TLSRoute to forward TLS traffic based on the Server Name
Indication (SNI) of the incoming connection. Envoy Gateway resolves the upstream host from the SNI and forwards the
TLS bytes unchanged (TLS passthrough), without needing prior knowledge of the destination hostnames.
Under the hood, Envoy Gateway uses the Envoy SNI Dynamic Forward Proxy
network filter. The upstream connection always targets port 443. Loopback hostnames/addresses (for example localhost,
127.0.0.1, ::1) presented as the SNI are denied by default so they cannot route to the proxy’s own loopback interface.
The referenced Backend must be the only backend of the route, and the parent Gateway listener must use TLS Passthrough
mode.
BackendUtilization load balancing uses Open Resource Cost Application (ORCA) load metrics reported by the backend to dynamically weight endpoints. Under the hood it is implemented as Envoy’s client-side weighted round-robin policy: each endpoint’s weight is derived from the utilization metrics it emits, so instances running hot receive proportionally less traffic than those with headroom.
If no ORCA metrics are received from an endpoint, that endpoint is treated as evenly weighted.
Your backend (or a sidecar in front of it) must report ORCA load metrics — either in-band as response headers or trailers, or out-of-band by implementing the OpenRcaService gRPC stream. See Backend instrumentation and Out-of-Band (OOB) Reporting below.
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Build and Deploy the Example Backend
The Envoy Gateway repository includes a small HTTP server under examples/backend-utilization/ that emits a fixed ORCA cpu_utilization value (set via the ORCA_CPU_UTILIZATION environment variable) on every response. The example manifest deploys two sets of pods — one reporting 0.1 (idle) and one reporting 0.9 (hot) — behind a single Service. This lets you observe the weighting effect without wiring real load into a backend.
The same server also implements the OpenRcaService gRPC stream on port 3001 for out-of-band reporting, and accepts ORCA_INBAND=false to turn the response headers off so that OOB is the only source of metrics.
Note: The envoyproxy/gateway-backend-utilization image is not published to a public registry — you need to build it locally from a checkout of the Envoy Gateway repository.
Build the example backend image
make -C examples/backend-utilization docker-buildx
---apiVersion:gateway.envoyproxy.io/v1alpha1kind:BackendTrafficPolicymetadata:name:backend-utilizationnamespace:defaultspec:targetRefs:- group:gateway.networking.k8s.iokind:HTTPRoutename:backend-utilizationloadBalancer:type:BackendUtilizationbackendUtilization:blackoutPeriod:1s # shorten so the demo shifts traffic quicklyweightUpdatePeriod:500ms
Leaving backendUtilization: {} empty accepts the defaults, but the 10 s default blackoutPeriod means traffic will appear evenly split for the first 10 seconds of the test. The shorter values above make the weighting visible immediately. The backendUtilization field itself is required when type: BackendUtilization — omitting it will fail CEL validation.
Configuration Fields
All fields on backendUtilization are optional.
Field
Default
Purpose
blackoutPeriod
10s
How long an endpoint must report metrics before its reported weight is trusted. Prevents traffic from shifting based on a single noisy sample.
weightExpirationPeriod
3m
If an endpoint stops reporting for this long, its reported weight is discarded and it reverts to the default weight.
weightUpdatePeriod
1s
How often Envoy recomputes the weight table. Values below 100ms are capped at 100ms.
errorUtilizationPenaltyPercent
0
Multiplier (as percent × 100) applied to an endpoint’s effective utilization based on its error rate (eps/qps). 100 = 1.0×, 150 = 1.5×, 200 = 2.0×. Higher values push errant endpoints out of rotation faster.
metricNamesForComputingUtilization
unset
Custom ORCA metric keys to feed into the weight formula when application_utilization isn’t reported. Use named_metrics.<key> for keys inside the ORCA proto’s named_metrics map.
keepResponseHeaders
false
By default Envoy strips the ORCA headers/trailers before forwarding the response. Set to true to let downstream clients see them (useful for chained load balancers or debugging).
outOfBand
unset
Enables out-of-band ORCA reporting — Envoy also streams load reports from the endpoint’s OpenRcaService on a schedule, in addition to any in-band metrics carried in response headers/trailers.
Example: Tuned for a Bursty Backend
loadBalancer:type:BackendUtilizationbackendUtilization:blackoutPeriod:30s # ignore reports during slow-startweightExpirationPeriod:1m # shorter memory — react faster to silent endpointsweightUpdatePeriod:500ms # faster reweightingerrorUtilizationPenaltyPercent:150# 1.5× penalty for errant endpoints
Example: Application-Defined Utilization
If your backend reports a custom metric (for example, queue depth) instead of CPU utilization, wire it in through metricNamesForComputingUtilization:
TEXT cpu=0.3,mem=0.8,named_metrics.queue_depth=0.42
For gRPC backends, the xDS ORCA libraries emit these automatically via the orca_load_report service. For HTTP backends, add a response middleware that measures and serializes your CPU/memory/custom metrics on each response.
Out-of-Band (OOB) Reporting
By default Envoy reads ORCA metrics in-band — from the response headers or trailers of regular requests (see Backend Instrumentation above). With out-of-band (OOB) reporting, Envoy additionally opens a dedicated server-streaming gRPC connection to each endpoint’s OpenRcaService (xds.service.orca.v3.OpenRcaService/StreamCoreMetrics) and receives load reports on a fixed schedule, independent of request traffic.
OOB reporting is useful when:
Request volume is low or bursty, so in-band samples arrive too infrequently to weight endpoints well.
You want load signals even for endpoints that are currently idle.
A separate reporting sidecar exposes the ORCA stream on its own port.
Enable it by adding an outOfBand block. Its presence turns OOB on; an empty outOfBand: {} enables it with Envoy’s defaults.
OOB supplements in-band reporting, it does not replace it: Envoy keeps consuming ORCA metrics from response headers/trailers (and keepResponseHeaders still applies), and reports from either source feed the same endpoint weight table. Enabling OOB is therefore safe for a backend that already reports in-band — it only adds a second, traffic-independent source of samples.
loadBalancer:type:BackendUtilizationbackendUtilization:outOfBand:reportingPeriod:5s # how often Envoy requests a report (default 10s)port: 9001 # optional:reach a reporting sidecar on a different portauthority: orca.example.com # optional::authority header for the OOB gRPC stream
Field
Default
Purpose
outOfBand.reportingPeriod
10s
How often Envoy requests a load report from the endpoint. The server may report less frequently than requested. Must be greater than 0.
outOfBand.port
endpoint port
Alternative port for the OOB reporting connection, e.g. a dedicated reporting sidecar. Must be between 1 and 65535. Ignored for non-IP (pipe/UDS) endpoint addresses.
outOfBand.authority
unset
Overrides the :authority header on the OOB gRPC stream. When unset, Envoy uses the endpoint hostname, then the dialed address, then the cluster name. Must be 1–259 characters and contain no NUL, CR or LF.
Choosing a Reporting Period
reportingPeriod interacts with two of the fields above, and neither interaction is validated for you:
Keep it comfortably below weightExpirationPeriod (default 3m). Weights are discarded once an endpoint has gone that long without reporting, so a reportingPeriod at or above the expiration window leaves endpoints sitting at their fallback weight for most of their life — BackendUtilization quietly degrades to plain round-robin.
Compare it against blackoutPeriod (default 10s). An endpoint’s weight is not used until it has been reporting continuously for the blackout period, so a reportingPeriod larger than blackoutPeriod delays the first weighted routing decision by at least one full period after startup.
Envoy caps nothing here: a reportingPeriod of 10m against the default 3m expiration is accepted by both the API and Envoy, and simply produces unweighted round-robin between reports.
Trying It With the Example Backend
The example backend serves OpenRcaService on port 3001, so point outOfBand.port at it:
Set ORCA_INBAND=false on the example Deployments if you want to confirm the traffic skew is coming from the OOB stream rather than from response headers.
Your backend must implement the OpenRcaService streaming RPC for OOB to take effect. gRPC backends can use the xDS ORCA server libraries; the same OrcaLoadReport message carries both in-band and OOB reports.
The reporting stream reuses the transport socket Envoy already uses for that endpoint, so upstream TLS (from a BackendTLSPolicy) applies to the OOB connection as well. If you point port at a separate reporting sidecar, that sidecar is dialed with the same transport socket and must therefore accept the same TLS configuration.
Combining With Zone-Aware Routing
BackendUtilization composes with weightedZones to produce locality-aware weighted round-robin (Envoy’s wrr_locality policy). See the WeightedZones example on the zone-aware routing page.
preferLocal is not supported with BackendUtilization.
Testing
Ensure the GATEWAY_HOST environment variable from the Quickstart is set. If not, follow the Quickstart instructions to set the variable.
Give Envoy a few seconds after applying the policy to collect ORCA samples and compute endpoint weights — until then, traffic will appear roughly even. Then send 200 requests and tally which deployment handled each. Because backend-utilization-low reports cpu_utilization=0.1 and backend-utilization-high reports 0.9, Envoy should weight the low pods roughly 9× more heavily.
for i in $(seq 1 200);do curl -s -H "Host: www.example.com""http://${GATEWAY_HOST}/backend-utilization"| jq -r '.pod'done| sort | uniq -c
Expected output (exact counts will vary, but low should dominate ~9:1):
If you instead see a roughly even split, the weights may not have stabilized yet — wait a few seconds and retry. You can verify the per-endpoint weights directly through the Envoy admin interface:
Bandwidth limit allows users to control the throughput of traffic sent to and received from backends.
Envoy throttles matching request or response bodies by pausing data transfer when the configured bandwidth is exhausted, resuming as tokens are replenished, so clients generally see slower transfers rather than bandwidth-limit rejections.
Note: The bandwidth limit is applied per Envoy proxy instance.
If the data plane runs multiple replicas, each replica enforces the limit independently.
When a BackendTrafficPolicy with bandwidthLimit targets a Gateway, Envoy Gateway applies the same limit to each matching route under that Gateway.
The limit is not shared across routes.
Prerequisites
Install Envoy Gateway
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
Total size in bytes of outgoing request data from bandwidth limiter
Limit Response Bandwidth
The following example limits outbound response traffic to 1 KiB/s and adds response trailers, so clients can observe the delay introduced by the filter.
Deploy httpbin as a backend. Its /bytes/{n} endpoint returns exactly n bytes, making it easy to generate large responses on demand:
At least one of request or response must be specified.
Bandwidth Limit Values
The value field accepts Kubernetes resource quantity notation.
The unit field controls the time window: Second, Minute, or Hour.
2.2.4 - Circuit Breakers
Envoy Circuit Breakers can be used to fail quickly and apply back-pressure in response to upstream service degradation.
Envoy Gateway supports the following circuit breaker thresholds:
Concurrent Connections: limit the connections that Envoy can establish to the upstream service. When this threshold is met, new connections will not be established, and some requests will be queued until an existing connection becomes available.
Concurrent Requests: limit on concurrent requests in-flight from Envoy to the upstream service. When this threshold is met, requests will be queued.
Pending Requests: limit the pending request queue size. When this threshold is met, overflowing requests will be terminated with a 503 status code.
Envoy’s circuit breakers are distributed: counters are not synchronized across different Envoy processes. The default Envoy and Envoy Gateway circuit breaker threshold values (1024) may be too strict for high-throughput systems.
Envoy Gateway introduces a new CRD called BackendTrafficPolicy that allows the user to describe their desired circuit breaker thresholds.
This instantiated resource can be linked to a Gateway, HTTPRoute or GRPCRoute resource.
Note: There are distinct circuit breaker counters for each BackendReference in an xRoute rule. Even if a BackendTrafficPolicy targets a Gateway, each BackendReference in that gateway still has separate circuit breaker counter.
Prerequisites
Install Envoy Gateway
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Install the hey load testing tool
The hey CLI will be used to generate load and measure response times. Follow the installation instruction from the Hey project docs.
Test and customize circuit breaker settings
This example will simulate a degraded backend that responds within 10 seconds by adding the ?delay=10s query parameter to API calls. The hey tool will be used to generate 100 concurrent requests.
The default circuit breaker threshold (1024) is not met. As a result, requests do not overflow: all requests are proxied upstream and both Envoy and clients wait for 10s.
In order to fail fast, apply a BackendTrafficPolicy that limits concurrent requests to 10 and pending requests to 0.
With the new circuit breaker settings, and due to the slowness of the backend, only the first 10 concurrent requests were proxied, while the other 90 overflowed.
The ClientTrafficPolicy API allows system administrators to configure
the behavior for how the Envoy Proxy server behaves with downstream clients.
Motivation
This API was added as a new policy attachment resource that can be applied to Gateway resources and it is meant to hold settings for configuring behavior of the connection between the downstream client and Envoy Proxy listener. It is the counterpart to the BackendTrafficPolicy API resource.
Quickstart
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
* Trying 172.18.255.202:80...
* Connected to 172.18.255.202 (172.18.255.202) port 80(#0)> GET /get HTTP/1.1
> Host: www.example.com
> User-Agent: curl/8.1.2
> Accept: */*
>
* Recv failure: Connection reset by peer
* Closing connection 0curl: (56) Recv failure: Connection reset by peer
Curl the example app through Envoy proxy once again, now sending HAProxy PROXY protocol header at the beginning of the connection with –haproxy-protocol flag:
If numTrustedHops is set to N, the client IP is taken from the Nth address from the right end of the XFF header. In this example,
we set numTrustedHops to 2, so the client IP will be taken from the second rightmost address in the XFF header.
To stop Envoy Gateway from automatically appending the downstream client address to X-Forwarded-For,
set spec.clientIPDetection.xForwardedFor.disableXForwardedForAppend: true in the same ClientTrafficPolicy.
This only disables the automatic append behavior and does not remove or sanitize an incoming
X-Forwarded-For header.
You should expect 200 response status, see that X-Forwarded-Proto was preserved and X-Envoy-External-Address was set to the
second rightmost address in the X-Forwarded-For header:
This feature allows you to limit the time taken by the Envoy Proxy fleet to receive the entire request from the client, which is useful in preventing certain clients from consuming too much memory in Envoy
This example configures the HTTP request timeout for the client, please check out the details here.
The idle timeout is defined as the period in which there are no active requests. When the idle timeout is reached the connection will be closed.
For more details see here.
You should expect the connection to be closed after 5s.
You can also check the number of connections closed due to idle timeout by using the following query:
envoy_http_downstream_cx_idle_timeout{envoy_http_conn_manager_prefix="<name of connection manager>"}
The number of connections closed due to idle timeout should be increased by 1.
Configure Downstream Per Connection Buffer Limit
This feature allows you to set a soft limit on size of the listener’s new connection read and write buffers.
The size is configured using the resource.Quantity format, see examples here.
This feature allows you to configure the maximum size of the request headers allowed for incoming connections, mapping to the Envoy max_request_headers_kb HTTP connection manager setting.
Requests whose headers exceed this limit receive a 431 (Request Header Fields Too Large) response.
The value is configured using the resource.Quantity format and is rounded up to the nearest KiB. It must be at least 1Ki and cannot exceed 8192Ki (the maximum Envoy supports). When no suffix is provided, the value is interpreted as bytes. If unset, Envoy Gateway defaults to 60Ki.
You should expect a 431 response status once the combined request header size exceeds 96Ki:
< HTTP/1.1 431 Request Header Fields Too Large
< content-length: 31< content-type: text/plain
<
Request Header Fields Too Large
Note
Only one ClientTrafficPolicy can set maxRequestHeaderLimit per Envoy listener. When multiple plaintext (HTTP, non-TLS) listeners on the same Gateway share the same port, only a Gateway-scoped (not listener/sectionName-scoped) ClientTrafficPolicy may set this field, since Envoy Gateway collapses same-port plaintext listeners into a single Envoy listener.
2.2.6 - Connection Limit
The connection limit features allows users to limit the number of concurrently active TCP connections on a Gateway or a Listener.
When the connection limit is reached, new connections are closed immediately by Envoy proxy. It’s possible to configure a delay for connection rejection.
Users may want to limit the number of connections for several reasons:
Protect resources like CPU and Memory.
Ensure that different listeners can receive a fair share of global resources.
Protect from malicious activity like DoS attacks.
Envoy Gateway introduces a new CRD called Client Traffic Policy that allows the user to describe their desired connection limit settings.
This instantiated resource can be linked to a Gateway.
The Envoy connection limit implementation is distributed: counters are not synchronized between different envoy proxies.
When a Client Traffic Policy is attached to a gateway, the connection limit will apply differently based on the
Listener protocol in use:
HTTP: all HTTP listeners in a Gateway will share a common connection counter, and a limit defined by the policy.
HTTPS/TLS: each HTTPS/TLS listener will have a dedicated connection counter, and a limit defined by the policy.
Prerequisites
Install Envoy Gateway
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
With the new connection limit, only 5 of 10 connections are established, and so only 50 requests succeed.
2.2.7 - Direct Response
Direct responses are valuable in cases where you want the gateway itself
to handle certain requests without forwarding them to backend services.
This task shows you how to configure them.
The HTTPRouteFilter used below can also be referenced from a GRPCRoute via an extensionRef filter. For gRPC, Envoy
adds gRPC status trailers to the direct response so gRPC clients handle it correctly. See
Gateway API support for details.
Installation
Follow the steps from the Quickstart to install Envoy Gateway and the example manifest.
Before proceeding, you should be able to query the example backend using HTTP.
Testing Direct Response
There is no fixed size limit for direct-response bodies, but they are stored in Envoy’s memory, so avoid using very large responses.
Save and apply the following resource to your cluster:
---apiVersion:gateway.networking.k8s.io/v1kind:HTTPRoutemetadata:name:direct-responsespec:parentRefs:- name:eghostnames:- "www.example.com"rules:- matches:- path:type:PathPrefixvalue:/inlinefilters:- type:ExtensionRefextensionRef:group:gateway.envoyproxy.iokind:HTTPRouteFiltername:direct-response-inline- matches:- path:type:PathPrefixvalue:/value-reffilters:- type:ExtensionRefextensionRef:group:gateway.envoyproxy.iokind:HTTPRouteFiltername:direct-response-value-ref---apiVersion:v1kind:ConfigMapmetadata:name:value-ref-responsedata:response.body:'{"error": "Internal Server Error"}'---apiVersion:gateway.envoyproxy.io/v1alpha1kind:HTTPRouteFiltermetadata:name:direct-response-inlinespec:directResponse:contentType:text/plainstatusCode:503body:type:Inlineinline:"Oops! Your request is not found."---apiVersion:gateway.envoyproxy.io/v1alpha1kind:HTTPRouteFiltermetadata:name:direct-response-value-refspec:directResponse:contentType:application/jsonstatusCode:500body:type:ValueRefvalueRef:group:""kind:ConfigMapname:value-ref-response
* Trying 127.0.0.1:80...
* Connected to 127.0.0.1 (127.0.0.1) port 80
> GET /value-ref HTTP/1.1
> Host: www.example.com
> User-Agent: curl/8.4.0
> Accept: */*
>< HTTP/1.1 500 Internal Server Error
< content-type: application/json
< content-length: 34
< date: Sat, 02 Nov 2024 00:35:55 GMT
<
* Connection #0 to host 127.0.0.1 left intact
{"error": "Internal Server Error"}
2.2.8 - Failover
Active-passive failover in an API gateway setup is like having a backup plan in place to keep things
running smoothly if something goes wrong. Here’s why it’s valuable:
Staying Online: When the main (or “active”) backend has issues or goes offline,
the fallback (or “passive”) backend is ready to step in instantly.
This helps keep your API accessible and your services running, so users don’t even notice any interruptions.
Automatic Switch Over: If a problem occurs, the system can automatically switch traffic over to the fallback backend.
This avoids needing someone to jump in and fix things manually, which could take time and might even lead to mistakes.
Lower Costs: In an active-passive setup, the fallback backend doesn’t need to work all the time—it’s just on standby.
This can save on costs (like cloud egress costs) compared to setups where both backend are running at full capacity.
Peace of Mind with Redundancy: Although the fallback backend isn’t handling traffic daily, it’s there as a safety net.
If something happens with the primary backend, the backup can take over immediately, ensuring your service doesn’t skip a beat.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
Follow the instructions here to enable the Backend API
Create two Backend resources that are used to represent the active backend and passive backend.
Note, we’ve set fallback: true for the passive backend to indicate its a passive backend
Lets send 10 requests again. You should see them all being sent to the passive backend
for i in {1..10;do curl --verbose --header "Host: www.example.com" http://$GATEWAY_HOST/test 2>/dev/null | jq .pod;done
parse error: Invalid numeric literal at line 1, column 9
"passive-7ddbf945c9-wkc4f"
"passive-7ddbf945c9-wkc4f"
"passive-7ddbf945c9-wkc4f"
"passive-7ddbf945c9-wkc4f"
"passive-7ddbf945c9-wkc4f"
"passive-7ddbf945c9-wkc4f"
"passive-7ddbf945c9-wkc4f"
"passive-7ddbf945c9-wkc4f"
"passive-7ddbf945c9-wkc4f"
The first error can be avoided by configuring retries.
2.2.9 - Fault Injection
Envoy fault injection can be used to inject delays and abort requests to mimic failure scenarios such as service failures and overloads.
Envoy Gateway supports the following fault scenarios:
delay fault: inject a custom fixed delay into the request with a certain probability to simulate delay failures.
abort fault: inject a custom response code into the response with a certain probability to simulate abort failures.
Envoy Gateway introduces a new CRD called BackendTrafficPolicy that allows the user to describe their desired fault scenarios.
This instantiated resource can be linked to a Gateway, HTTPRoute or GRPCRoute resource.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
Two HTTPRoute resources were created, one for /foo and another for /bar. fault-injection-abort BackendTrafficPolicy has been created and targeted HTTPRoute foo to abort requests for /foo. fault-injection-delay BackendTrafficPolicy has been created and targeted HTTPRoute foo to delay 2s requests for /bar.
Verify the HTTPRoute configuration and status:
kubectl get httproute/foo -o yaml
kubectl get httproute/bar -o yaml
Verify the BackendTrafficPolicy configuration:
kubectl get backendtrafficpolicy/fault-injection-50-percent-abort -o yaml
kubectl get backendtrafficpolicy/fault-injection-delay -o yaml
The Gateway API provides an optional Addresses field through which Envoy Gateway can set addresses for Envoy Proxy Service.
Depending on the Service Type, the addresses of gateway can be used as:
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
External IPs
Using the addresses in Gateway.Spec.Addresses as the External IPs of Envoy Proxy Service,
this will require the address to be of type IPAddress and the ServiceType to be of LoadBalancer or NodePort.
The Envoy Gateway deploys Envoy Proxy Service as LoadBalancer by default,
so you can set the address of the Gateway directly (the address settings here are for reference only):
NAME CLASS ADDRESS PROGRAMMED AGE
eg eg 1.2.3.4 True 14m
Verify the Envoy Proxy Service status:
kubectl get service -n envoy-gateway-system
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
envoy-default-eg-64656661 LoadBalancer 10.96.236.219 1.2.3.4 80:31017/TCP 15m
envoy-gateway ClusterIP 10.96.192.76 <none> 18000/TCP 15m
envoy-gateway-metrics-service ClusterIP 10.96.124.73 <none> 8443/TCP 15m
Note: If the Gateway.Spec.Addresses is explicitly set, it will be the only addresses that populates the Gateway status.
Cluster IP
Using the addresses in Gateway.Spec.Addresses as the Cluster IP of Envoy Proxy Service,
this will require the address to be of type IPAddress and the ServiceType to be of ClusterIP.
2.2.11 - Global Rate Limit
Rate limit is a feature that allows the user to limit the number of incoming requests to a predefined value based on attributes within the traffic flow.
Here are some reasons why you may want to implement Rate limits
To prevent malicious activity such as DDoS attacks.
To prevent applications and its resources (such as a database) from getting overloaded.
Global rate limiting applies a shared rate limit to the traffic flowing through all the instances of Envoy proxies where it is configured.
i.e. if the data plane has 2 replicas of Envoy running, and the rate limit is 10 requests/second, this limit is shared and will be hit
if 5 requests pass through the first replica and 5 requests pass through the second replica within the same second.
Envoy Gateway introduces a new CRD called BackendTrafficPolicy that allows the user to describe their rate limit intent. This instantiated resource
can be linked to a Gateway, HTTPRoute or GRPCRoute resource.
Note: Limit is applied per route. Even if a BackendTrafficPolicy targets a gateway, each route in that gateway
still has a separate rate limit bucket. For example, if a gateway has 2 routes, and the limit is 100r/s, then each route
has its own 100r/s rate limit bucket.
Prerequisites
Install Envoy Gateway
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Install Redis
The global rate limit feature is based on Envoy Ratelimit which requires a Redis instance as its caching layer.
Lets install a Redis deployment in the redis-system namespce.
The default installation of Envoy Gateway installs a default EnvoyGateway configuration and attaches it
using a ConfigMap. To enable global rate limit, we need to update this configuration to configure the Redis service
as the backend for rate limit.
Alternatively, instead of a literal url, you can source the Redis URL from a
Secret key with urlRef. This is useful for GitOps workflows where the Redis
endpoint is provisioned dynamically by an external controller (for example,
Crossplane writing a connection Secret). The referenced Secret must exist in
the Envoy Gateway namespace (envoy-gateway-system), and url and urlRef are
mutually exclusive:
After updating the ConfigMap, you will need to wait the configuration kicks in. You can force the configuration to be reloaded by restarting the envoy-gateway deployment.
Here is an example of a rate limit implemented by the application developer to limit a specific user by matching on a custom x-user-id header
with a value set to one.
The HTTPRoute status should indicate that it has been accepted and is bound to the example Gateway.
kubectl get httproute/http-ratelimit -o yaml
Get the Gateway’s address:
exportGATEWAY_HOST=$(kubectl get gateway/eg -o jsonpath='{.status.addresses[0].value}')
Let’s query ratelimit.example/get 4 times. We should receive a 200 response from the example Gateway for the first 3 requests
and then receive a 429 status code for the 4th request since the limit is set at 3 requests/Hour for the request which contains the header x-user-id
and value one.
for i in {1..4};do curl -I --header "Host: ratelimit.example" --header "x-user-id: one" http://${GATEWAY_HOST}/get ; sleep 1;done
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:31 GMT
content-length: 460
x-envoy-upstream-service-time: 4
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:32 GMT
content-length: 460
x-envoy-upstream-service-time: 2
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:33 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 429 Too Many Requests
x-envoy-ratelimited: true
date: Wed, 08 Feb 2023 02:33:34 GMT
server: envoy
transfer-encoding: chunked
You should be able to send requests with the x-user-id header and a different value and receive successful responses from the server.
for i in {1..4};do curl -I --header "Host: ratelimit.example" --header "x-user-id: two" http://${GATEWAY_HOST}/get ; sleep 1;done
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:34:36 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:34:37 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:34:38 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:34:39 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
Rate Limit Distinct Users Except Admin
Here is an example of a rate limit implemented by the application developer to limit distinct users who can be differentiated based on the
value in the x-user-id header. Here, user one (recognised from the traffic flow using the header x-user-id and value one) will be rate limited at 3 requests/hour
and so will user two (recognised from the traffic flow using the header x-user-id and value two). But if x-user-id is admin, it will not be rate limited even beyond 3 requests/hour.
The invert: true field inverts the header match condition. Instead of matching requests where x-user-id is admin, it matches requests where x-user-id is notadmin. In this example, the rate limit applies to all distinct users except admin.
Lets run the same command again with the header x-user-id and value one set in the request. We should the first 3 requests succeeding and
the 4th request being rate limited.
for i in {1..4};do curl -I --header "Host: ratelimit.example" --header "x-user-id: one" http://${GATEWAY_HOST}/get ; sleep 1;done
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:31 GMT
content-length: 460
x-envoy-upstream-service-time: 4
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:32 GMT
content-length: 460
x-envoy-upstream-service-time: 2
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:33 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 429 Too Many Requests
x-envoy-ratelimited: true
date: Wed, 08 Feb 2023 02:33:34 GMT
server: envoy
transfer-encoding: chunked
You should see the same behavior when the value for header x-user-id is set to two and 4 requests are sent.
for i in {1..4};do curl -I --header "Host: ratelimit.example" --header "x-user-id: two" http://${GATEWAY_HOST}/get ; sleep 1;done
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:31 GMT
content-length: 460
x-envoy-upstream-service-time: 4
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:32 GMT
content-length: 460
x-envoy-upstream-service-time: 2
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:33 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 429 Too Many Requests
x-envoy-ratelimited: true
date: Wed, 08 Feb 2023 02:33:34 GMT
server: envoy
transfer-encoding: chunked
But when the value for header x-user-id is set to admin and 4 requests are sent, all 4 of them should respond with 200 OK.
for i in {1..4};do curl -I --header "Host: ratelimit.example" --header "x-user-id: admin" http://${GATEWAY_HOST}/get ; sleep 1;done
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:31 GMT
content-length: 460
x-envoy-upstream-service-time: 4
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:32 GMT
content-length: 460
x-envoy-upstream-service-time: 2
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:33 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:33 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
Rate Limit All Requests
This example shows you how to rate limit all requests matching the HTTPRoute rule at 3 requests/Hour by leaving the clientSelectors field unset.
for i in {1..4};do curl -I --header "Host: ratelimit.example" http://${GATEWAY_HOST}/get ; sleep 1;done
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:31 GMT
content-length: 460
x-envoy-upstream-service-time: 4
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:32 GMT
content-length: 460
x-envoy-upstream-service-time: 2
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:33 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 429 Too Many Requests
x-envoy-ratelimited: true
date: Wed, 08 Feb 2023 02:33:34 GMT
server: envoy
transfer-encoding: chunked
Rate Limit Client IP Addresses
Here is an example of a rate limit implemented by the application developer to limit distinct users who can be differentiated based on their
IP address (also reflected in the X-Forwarded-For header).
Note: EG supports two kinds of rate limit for the IP address: Exact and Distinct.
Exact means that all IP addresses within the specified Source IP CIDR share the same rate limit bucket.
Distinct means that each IP address within the specified Source IP CIDR has its own rate limit bucket.
for i in {1..4};do curl -I --header "Host: ratelimit.example" http://${GATEWAY_HOST}/get ; sleep 1;done
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Tue, 28 Mar 2023 08:28:45 GMT
content-length: 512
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Tue, 28 Mar 2023 08:28:46 GMT
content-length: 512
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Tue, 28 Mar 2023 08:28:48 GMT
content-length: 512
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 429 Too Many Requests
x-envoy-ratelimited: true
date: Tue, 28 Mar 2023 08:28:48 GMT
server: envoy
transfer-encoding: chunked
Rate Limit Based on Path
Here is an example of a rate limit implemented by the application developer to limit requests based on the request path. In this case, we are limiting requests to /api/users to 3 requests/Hour.
PathPrefix: Matches paths with a specific prefix (e.g., /api/)
RegularExpression: Matches paths using regex patterns (e.g., /api/users/[0-9]+)
Let’s query /api/users 4 times and /api/products 4 times. We should receive a 200 response for the first 3 requests to /api/users
and a 429 status code for the 4th request. Requests to /api/products should not be rate limited:
# First, test the rate-limited path /api/users - 4 requests (4th should be rate limited)for i in {1..4};do curl -I --header "Host: ratelimit.example" http://${GATEWAY_HOST}/api/users ; sleep 1;done# Now test a different path that should not be rate limitedfor i in {1..4};do curl -I --header "Host: ratelimit.example" http://${GATEWAY_HOST}/api/products ; sleep 1;done
# Requests to /api/users (rate limited after 3 requests)HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:31 GMT
content-length: 460
x-envoy-upstream-service-time: 4
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:32 GMT
content-length: 460
x-envoy-upstream-service-time: 2
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:33 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 429 Too Many Requests
x-envoy-ratelimited: true
date: Wed, 08 Feb 2023 02:33:34 GMT
server: envoy
transfer-encoding: chunked
# Requests to /api/products (not rate limited)HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:35 GMT
content-length: 460
x-envoy-upstream-service-time: 4
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:36 GMT
content-length: 460
x-envoy-upstream-service-time: 2
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:37 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:38 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
You can see that requests to /api/users are rate limited after the 3rd request (returning 429), while all requests to /api/products succeed without any rate limit.
Rate Limit Based on HTTP Method
Here is an example of a rate limit implemented by the application developer to limit requests based on the HTTP method. In this case, we are limiting POST requests to 3 requests/Hour.
Let’s query the same path with POST and GET methods. We should receive a 200 response for the first 3 POST requests
and a 429 status code for the 4th POST request. GET requests should not be rate limited:
# Send 4 POST requests - the 4th one should be rate limitedfor i in {1..4};do curl -X POST -I --header "Host: ratelimit.example" http://${GATEWAY_HOST}/api/data ; sleep 1;done# GET requests should not be rate limitedfor i in {1..4};do curl -X GET -I --header "Host: ratelimit.example" http://${GATEWAY_HOST}/api/data ; sleep 1;done
# POST requests (rate limited after 3 requests)HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:31 GMT
content-length: 460
x-envoy-upstream-service-time: 4
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:32 GMT
content-length: 460
x-envoy-upstream-service-time: 2
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:33 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 429 Too Many Requests
x-envoy-ratelimited: true
date: Wed, 08 Feb 2023 02:33:34 GMT
server: envoy
transfer-encoding: chunked
# GET requests (not rate limited)HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:35 GMT
content-length: 460
x-envoy-upstream-service-time: 4
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:36 GMT
content-length: 460
x-envoy-upstream-service-time: 2
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:37 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:38 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
You can see that POST requests are rate limited after the 3rd request (returning 429), while GET requests to the same path are not rate limited.
Rate Limit Jwt Claims
Here is an example of a rate limit implemented by the application developer to limit distinct users who can be differentiated based on the value of the Jwt claims carried.
for i in {1..4};do curl -I --header "Host: ratelimit.example" --header "Authorization: Bearer $TOKEN" http://${GATEWAY_HOST}/foo ; sleep 1;done
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Mon, 12 Jun 2023 12:00:25 GMT
content-length: 561
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Mon, 12 Jun 2023 12:00:26 GMT
content-length: 561
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Mon, 12 Jun 2023 12:00:27 GMT
content-length: 561
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 429 Too Many Requests
x-envoy-ratelimited: true
date: Mon, 12 Jun 2023 12:00:28 GMT
server: envoy
transfer-encoding: chunked
No Rate Limit by carrying TOKEN1
for i in {1..4};do curl -I --header "Host: ratelimit.example" --header "Authorization: Bearer $TOKEN1" http://${GATEWAY_HOST}/foo ; sleep 1;done
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Mon, 12 Jun 2023 12:02:34 GMT
content-length: 556
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Mon, 12 Jun 2023 12:02:35 GMT
content-length: 556
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Mon, 12 Jun 2023 12:02:36 GMT
content-length: 556
x-envoy-upstream-service-time: 1
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Mon, 12 Jun 2023 12:02:37 GMT
content-length: 556
x-envoy-upstream-service-time: 0
server: envoy
Limit Concurrent Requests per User
A rate limit counts requests per time window, so it doesn’t stop a client from keeping many slow requests open at the same time.
To limit the number of requests in flight instead, set a request cost and refundOnResponse: true on the same rule.
The counter is increased when a request starts and decreased again when the stream is closed, so it tracks the requests
that are currently open for each descriptor, and new requests are rate limited once it reaches the limit.
Here is an example that allows each distinct user, identified by the x-user-id header, to have at most 2 requests in flight.
Note: The rate limit service must support negative hits. The rate limit image that Envoy Gateway deploys by default does.
The example backend delays its response when the request has a delay query parameter. Let’s open 2 requests for user one
that take 10 seconds each, and send more requests while they are still open:
# Open 2 slow requests for user one in the backgroundfor i in {1..2};do curl -s -o /dev/null -w "one (slow): %{http_code}\n" --header "Host: ratelimit.example" --header "x-user-id: one""http://${GATEWAY_HOST}/get?delay=10s"&donesleep 1# User one already has 2 requests in flight, so this one is rate limitedcurl -s -o /dev/null -w "one: %{http_code}\n" --header "Host: ratelimit.example" --header "x-user-id: one" http://${GATEWAY_HOST}/get
# Other users are not affectedcurl -s -o /dev/null -w "two: %{http_code}\n" --header "Host: ratelimit.example" --header "x-user-id: two" http://${GATEWAY_HOST}/get
# Once the slow requests have finished, user one can send requests againwaitcurl -s -o /dev/null -w "one: %{http_code}\n" --header "Host: ratelimit.example" --header "x-user-id: one" http://${GATEWAY_HOST}/get
one: 429
two: 200
one (slow): 200
one (slow): 200
one: 200
The request cost is given back after the stream is closed, in a separate call to the rate limit service. If the last
request is sent right after the slow ones finish, it can still get a 429 until that call has been processed.
Keep the following in mind when using this pattern:
The counters still belong to a time window, so the limit is not a strict bound on concurrency when a new window starts.
The counter starts again from zero and the requests still open from the previous window are no longer counted. When
those requests end, their cost is given back to the counter of the new window, which cancels the cost of requests that
started in it. A client can then keep more requests in flight than the limit, by as many as it had open when the window
started, and this can add up over several windows if the client stays at the limit. Use a unit that is much longer
than your longest request, such as Hour, so that few requests are open when a window starts.
The decrease is sent to the rate limit service when the stream is closed and is not retried. If that call fails, the
counter stays higher than the real number of requests in flight until the window ends.
The descriptor is built again when the stream is closed, from the request headers as they are at that point. If the
route changes a header used by a clientSelectors entry, for example with a RequestHeaderModifier filter, the cost can
be given back to a different counter than the one that was increased.
The cost is given back even if the request was not counted when it started. By default, requests are let through when
the rate limit service can’t be reached, so a request that starts during an outage and ends after it lowers the counter
without having increased it. Setting failClosed: true in the rateLimit configuration of the EnvoyGateway resource
avoids this, at the cost of rejecting requests while the service is unavailable.
Rate Limit Policy Merging
This example demonstrates how to implement a layered rate limiting strategy using BackendTrafficPolicy merging. This approach allows platform teams to set global abuse prevention limits at the Gateway level, while application teams can define more specific rate limits for their individual routes.
In this scenario:
Platform Team: Manages a Gateway-level BackendTrafficPolicy that applies a global abuse rate limit (100 requests/second) across all traffic
Application Team: Manages a Route-level BackendTrafficPolicy that applies a more restrictive limit (5 requests/minute) for their specific signup service
The route-level policy uses mergeType: StrategicMerge to combine with the gateway-level policy, ensuring both limits are enforced. The global limit acts as an abuse prevention mechanism, while the route-specific limit protects the signup service from overload.
Gateway-level Policy: Uses shared: true to create a shared rate limit bucket that applies across all routes in the Gateway
Route-level Policy: Uses shared: false to create a dedicated rate limit bucket for this specific route
Merge Type: The mergeType: StrategicMerge field enables the route policy to merge with the gateway policy rather than override it
Testing the Merged Rate Limits
Let’s verify that both rate limits are enforced. The signup service should be limited to 5 requests per minute, but also subject to the global 100 requests/second abuse limit.
First, let’s test the route-specific limit by sending 6 requests within a minute:
for i in {1..6};do curl -I --header "Host: signup.example" http://${GATEWAY_HOST}/signup ; sleep 1;done
You should see the first 5 requests succeed and the 6th request receive a 429 Too Many Requests response:
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:31 GMT
content-length: 460
x-envoy-upstream-service-time: 4
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:32 GMT
content-length: 460
x-envoy-upstream-service-time: 2
server: envoy
...
HTTP/1.1 429 Too Many Requests
x-envoy-ratelimited: true
date: Wed, 08 Feb 2023 02:33:36 GMT
server: envoy
transfer-encoding: chunked
The global abuse limit would activate if traffic across all routes in the Gateway exceeds 100 requests/second, providing an additional layer of protection managed by the platform team.
Use Cases and Team Responsibilities
Platform Team Responsibilities:
Define Gateway-level policies with global abuse rate limits
Set reasonable baseline protections that apply to all applications
Use shared: true for limits that should be enforced across multiple routes
Monitor and adjust global limits based on infrastructure capacity
Application Team Responsibilities:
Define Route-level policies with application-specific rate limits
Use mergeType: StrategicMerge to combine with platform policies
Set shared: false for limits specific to their application’s requirements
Implement rate limits that protect their specific service from overload
This layered approach ensures both infrastructure protection and application-specific controls work together effectively.
(Optional) Editing Kubernetes Resources settings for the Rate Limit Service
The default installation of Envoy Gateway installs a default EnvoyGateway configuration and provides the initial rate
limit kubernetes resources settings. such as replicas is 1, requests resources cpu is 100m, memory is 512Mi. the others
like container image, securityContext, env and pod annotations and securityContext can be modified by modifying the ConfigMap.
tls.certificateRef set the client certificate for redis server TLS connections.
After updating the ConfigMap, you will need to wait the configuration kicks in. You can force the configuration to be reloaded by restarting the envoy-gateway deployment.
The GRPCRoute resource allows users to configure gRPC routing by matching HTTP/2 traffic and forwarding it to backend gRPC servers.
To learn more about gRPC routing, refer to the Gateway API documentation.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The manifest installs a GatewayClass, Gateway, a Deployment, a Service, and a GRPCRoute resource.
The GatewayClass is a cluster-scoped resource that represents a class of Gateways that can be instantiated.
Note: Envoy Gateway is configured by default to manage a GatewayClass with
controllerName: gateway.envoyproxy.io/gatewayclass-controller.
Verification
Check the status of the GatewayClass:
kubectl get gc --selector=example=grpc-routing
The status should reflect “Accepted=True”, indicating Envoy Gateway is managing the GatewayClass.
A Gateway represents configuration of infrastructure. When a Gateway is created, Envoy proxy infrastructure is
provisioned or configured by Envoy Gateway. The gatewayClassName defines the name of a GatewayClass used by this
Gateway. Check the status of the Gateway:
kubectl get gateways --selector=example=grpc-routing
The status should reflect “Ready=True”, indicating the Envoy proxy infrastructure has been provisioned. The status also
provides the address of the Gateway. This address is used later to test connectivity to proxied backend services.
Check the status of the GRPCRoute:
kubectl get grpcroutes --selector=example=grpc-routing -o yaml
The status for the GRPCRoute should surface “Accepted=True” and a parentRef that references the example Gateway.
The example-route matches any traffic for “grpc-example.com” and forwards it to the “yages” Service.
Testing the Configuration
Before testing GRPC routing to the yages backend, get the Gateway’s address.
exportGATEWAY_HOST=$(kubectl get gateway/example-gateway -o jsonpath='{.status.addresses[0].value}')
Test GRPC routing to the yages backend using the grpcurl command.
Envoy Gateway also supports gRPC-Web requests for this configuration. The below curl command can be used to send a grpc-Web request with over HTTP/2. You should receive the same response seen in the previous command.
The data in the body AAAAAAA= is a base64 encoded representation of an empty message (data length 0) that the Ping RPC accepts.
The matches field can be used to restrict the route to a specific set of requests based on GRPC’s service and/or method names.
It supports two match types: Exact and RegularExpression.
Exact
Exact match is the default match type.
The following example shows how to match a request based on the service and method names for grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo,
as well as a match for all services with a method name Ping which matches yages.Echo/Ping in our deployment.
The following example shows how to match a request based on the service and method names
with match type RegularExpression. It matches all the services and methods with pattern
/.*.Echo/Pin.+, which matches yages.Echo/Ping in our deployment.
Configuring or disabling timeouts with BackendTrafficPolicy
Streaming GRPC connections will often have lifespans longer than the default Envoy proxy timeout of 15 seconds. With Envoy Gateway, this timeout value can be configured using a BackendTrafficPolicy resource:
apiVersion:gateway.envoyproxy.io/v1alpha1kind:BackendTrafficPolicymetadata:name:configure-timeout-policyspec:targetRefs:- group:gateway.networking.k8s.iokind:GRPCRoutename:name-of-my-grpc-routetimeout:http:# Set to '0s' to disable timeoutsrequestTimeout:0s
2.2.13 - GRPC Timeouts
Unlike HTTPRoute, the Gateway API GRPCRoute resource does not (yet) expose a native
timeouts field — see the upstream tracking issue Support Request Timeouts for GRPCRoute.
Until that lands, Envoy Gateway lets you configure timeouts for gRPC traffic with a
BackendTrafficPolicy that targets the GRPCRoute.
The default request timeout is 15 seconds in Envoy Proxy, which will terminate long-lived
streaming RPCs. The relevant spec.timeout.http fields are:
requestTimeout: the maximum duration for the entire response to be received from the
upstream. This bounds unary RPCs. Set it to "0s" to disable it for streaming RPCs,
which otherwise would be cut off once the timeout elapses.
maxStreamDuration: the maximum duration of a stream, measured from when the request is sent
until the response stream is fully consumed. It does not apply to non-streaming requests. Set it
to "0s" to allow streams to run indefinitely.
streamIdleTimeout: the amount of time a stream may exist with no upstream or downstream
activity. Use this to reclaim idle streams without capping a healthy long-lived stream’s total
duration.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Follow the GRPC Routing task to set up a Gateway and a GRPCRoute named
yages before configuring timeouts.
Note: A GRPCRoute can have at most one BackendTrafficPolicy attached to it; a second policy
targeting the same route is rejected as Conflicted. The two examples below are therefore
alternatives that reuse the same policy name (grpc-timeouts) — pick the one that matches your
workload. Re-applying with the same metadata.name updates the existing policy rather than creating
a conflicting second one.
Unary RPCs
Set requestTimeout to bound the duration of unary RPCs. Here, unary calls that take longer than
5 seconds are terminated with a timeout.
For server-streaming, client-streaming, or bidirectional-streaming RPCs, requestTimeout would
terminate the stream once it elapses. Disable it with "0s" and, if you want an upper bound, use
maxStreamDuration (or streamIdleTimeout to reclaim only idle streams). The example below lets
streams run indefinitely while reclaiming streams that are idle for more than 1 hour.
cat <<EOF | kubectl apply -f -
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: BackendTrafficPolicy
metadata:
name: grpc-timeouts
spec:
targetRefs:
- group: gateway.networking.k8s.io
kind: GRPCRoute
name: yages
timeout:
http:
# Disable the per-request timeout so long-lived streams are not cut off.
requestTimeout: "0s"
# Allow streams to run indefinitely; set a non-zero value to cap them.
maxStreamDuration: "0s"
# Reclaim streams with no activity for more than 1 hour.
streamIdleTimeout: "1h"
EOF
Save and apply the following resource to your cluster:
---apiVersion:gateway.envoyproxy.io/v1alpha1kind:BackendTrafficPolicymetadata:name:grpc-timeoutsspec:targetRefs:- group:gateway.networking.k8s.iokind:GRPCRoutename:yagestimeout:http:# Disable the per-request timeout so long-lived streams are not cut off.requestTimeout:"0s"# Allow streams to run indefinitely; set a non-zero value to cap them.maxStreamDuration:"0s"# Reclaim streams with no activity for more than 1 hour.streamIdleTimeout:"1h"
Verification
First confirm the policy is accepted:
kubectl get backendtrafficpolicy/grpc-timeouts -o yaml
The status should reflect Accepted=True on the targeted GRPCRoute ancestor.
Then confirm the timeout is actually programmed into the Envoy route config with
egctl:
For the unary example you should see the route’s timeout set to the configured
requestTimeout (e.g. timeout: 5s). For the streaming example you should see
timeout: 0s (disabled) together with maxStreamDuration on the route action.
To exercise the timeout end-to-end you need a gRPC backend that can delay or stream (the
sample yages echo server used in the GRPC Routing task returns
immediately). Against such a backend, a unary call that exceeds requestTimeout returns
gRPC status DEADLINE_EXCEEDED (HTTP 504), for example with
grpcurl:
This task shows how to use HTTPRouteFilter to convert JSON/HTTP requests to gRPC requests, so REST
clients can call a gRPC backend.
The JSON/HTTP API is defined by the google.api.http options in your proto files.
The filter can only be used in the rule filters of an HTTPRoute. It is not supported in a GRPCRoute
or in the filters of a backendRef.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The descriptor set is read from the proto-descriptor key, either in binaryData or in data, where it can be
base64-encoded. If the ConfigMap has no data and only one binaryData entry, that entry is used.
Backend
The transcoded request is a gRPC request, so Envoy Gateway connects to the backend over HTTP/2, like the backend of a
GRPCRoute. No appProtocol is needed. A backend with a WebSocket app protocol, like appProtocol: kubernetes.io/ws,
can’t be used, because it needs HTTP/1.1.
Note: don’t set useClientProtocol in a BackendTrafficPolicy for the route. The client of the transcoder uses
HTTP/1.1 most of the time, so Envoy would send the gRPC requests over HTTP/1.1 and they would fail.
Configuration
Create an HTTPRouteFilter that references the ConfigMap, and use it in the HTTPRoute rule:
If services is not specified, all the services in the descriptor set are transcoded, except the ones that come from
imported files.
Policies and Routing
The transcoder changes the path of the request to the gRPC method, for example /example.Greeter/SayHello, but the
request is not matched to another route. The backend and the policies of the HTTPRoute are used for the transcoded
request, so attach the policies, like authentication and rate limiting, to the HTTPRoute. The policies of a GRPCRoute
for the same service are not applied.
Note: if EnvoyProxy.spec.filterOrder moves a filter that clears the route cache after the transcoder, like ExtAuth or
JWT with recomputeRoute, the transcoded request may be matched to another route.
The following filters can’t be used in the same rule with the transcoder, because they use the path of the request:
URLRewrite with a path modifier
URLRewrite with a PathRegex hostname
RequestRedirect
DirectResponse
Such a rule is not accepted and returns 500.
Note: a RequestMirror in the same rule sends the transcoded gRPC request to the mirror backend, over HTTP/2.
Troubleshooting
The descriptor set is validated when the route is translated. If it is invalid, the rule returns 500 and the reason is
in the Accepted condition of the HTTPRoute:
kubectl get httproute grpc-route -o yaml
These problems are reported:
The descriptor set can’t be parsed, or an imported file is missing.
An imported file comes after the file that imports it.
A service in services is not in the descriptor set.
The body or response_body of a google.api.http option is not a field of the message, or a response_body is not
a google.api.HttpBody field.
The path template of a google.api.http option is invalid, for example v1/hello without the leading /.
With convertGRPCStatus, the descriptor set conflicts with the google/protobuf/any.proto and
google/rpc/status.proto that Envoy adds. This happens when google.protobuf.Any is in another file, for example a
vendored third_party/google/protobuf/any.proto.
Note: the descriptor set should be generated by protoc. Envoy may still reject a descriptor set made by another tool
that protoc wouldn’t produce, for example with two fields that have the same JSON name. In that case, the whole
listener is rejected.
Clean-Up
Follow the steps from the Quickstart to uninstall Envoy Gateway and the example manifest.
Check out the Developer Guide to get involved in the project.
2.2.15 - Host Normalization
This task explains how to configure host normalization settings
using the ClientTrafficPolicy API.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Stripping Trailing Dot from the Host Header
Envoy does not strip trailing dots from the Host header by default, unlike some
other proxies (e.g. NGINX). This means requests with Host: example.com. will not
match routes with domains set to example.com. Use spec.headers.host.stripTrailingHostDot to
normalize these requests.
When the host includes a port (e.g. example.com.:443), only the trailing dot from
the host section is stripped, leaving the port as-is (example.com:443).
kubectl get clienttrafficpolicies.gateway.envoyproxy.io -n default
NAME STATUS AGE
strip-trailing-dot Accepted 5s
2.2.16 - HTTP CONNECT Tunnels
HTTP CONNECT tunnels are a mechanism that allows a client to establish a tunnel through an HTTP proxy server
to communicate directly with a destination server. This is commonly used for HTTPS traffic through proxies,
but can also be used for other protocols.
This task will help you get started using HTTP Connect based tunnels using Envoy Gateway.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The HTTPRoute resource can issue redirects to clients or rewrite paths sent upstream using filters. Note that
HTTPRoute rules cannot use both filter types at once. Currently, Envoy Gateway only supports coreHTTPRoute filters which consist of RequestRedirect and RequestHeaderModifier at the time of this writing. To
learn more about HTTP routing, refer to the Gateway API documentation.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Redirects
Redirects return HTTP 3XX responses to a client, instructing it to retrieve a different resource. A
RequestRedirect filter instructs Gateways to emit a redirect response to requests that match the rule.
For example, to issue a permanent redirect (301) from HTTP to HTTPS, configure requestRedirect.statusCode=301 and
requestRedirect.scheme="https":
If you followed the steps in the Secure Gateways task, you should be able to curl the redirect
location.
HTTP –> HTTPS
Listeners expose the TLS setting on a per domain or subdomain basis. TLS settings of a listener are applied to all domains that satisfy the hostname criteria.
Create a root certificate and private key to sign certificates:
Create the HTTPRoute to redirect requests to HTTPS and attach it to the HTTP listener using the sectionName field. The HTTPRoute has to be in the same namespace as the Gateway to be accepted.
Do not set hostnames field in the HTTPRoute - it will accept any http request to any hostname and redirect it to the same hostname over https.
Any other HTTPRoute resources deployed by Application Developers in any other namespace will automatically attach to the https section only, no need to set sectionName for them.
Path redirects use an HTTP Path Modifier to replace either entire paths or path prefixes. For example, the HTTPRoute
below will issue a 302 redirect to all path.redirect.example requests whose path begins with /get to /status/200.
The HTTPRoute status should indicate that it has been accepted and is bound to the example Gateway.
kubectl get httproute/http-filter-path-redirect -o yaml
Querying path.redirect.example should result in a 302 response from the example Gateway and a redirect location
containing the configured redirect path.
You should receive a 302 with a redirect location of http://path.redirect.example/status/200.
2.2.18 - HTTP Request Headers
The HTTPRoute resource can modify the headers of a request before forwarding it to the upstream service. HTTPRoute
rules cannot use both filter types at once. Currently, Envoy Gateway only supports coreHTTPRoute filters which
consist of RequestRedirect and RequestHeaderModifier at the time of this writing. To learn more about HTTP routing,
refer to the Gateway API documentation.
A RequestHeaderModifier filter instructs Gateways to modify the headers in requests that match the rule
before forwarding the request upstream. Note that the RequestHeaderModifier filter will only modify headers before the
request is sent from Envoy to the upstream service and will not affect response headers returned to the downstream
client. Header values support Envoy format strings, enabling dynamic values sourced from the
request and connection metadata.
According to RFC 9110 and RFC 7230, header names are case-insensitive, so each header only needs to be listed once (for example, x-forwarded-for also matches X-Forwarded-For).
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Adding Request Headers
The RequestHeaderModifier filter can add new headers to a request before it is sent to the upstream. If the request
does not have the header configured by the filter, then that header will be added to the request. If the request already
has the header configured by the filter, then the value of the header in the filter will be appended to the value of the
header in the request.
The HTTPRoute] status should indicate that it has been accepted and is bound to the example Gateway.
kubectl get httproute/http-headers -o yaml
Get the Gateway’s address:
exportGATEWAY_HOST=$(kubectl get gateway/eg -o jsonpath='{.status.addresses[0].value}')
Querying headers.example/get should result in a 200 response from the example Gateway and the output from the
example app should indicate that the upstream example app received the header add-header with the value:
something,foo
Setting headers is similar to adding headers. If the request does not have the header configured by the filter, then it
will be added, but unlike adding request headers which will append the value of the header if
the request already contains it, setting a header will cause the value to be replaced by the value configured in the
filter.
Querying headers.example/get should result in a 200 response from the example Gateway and the output from the
example app should indicate that the upstream example app received the header add-header with the original value
something replaced by foo.
Headers can be removed from a request by simply supplying a list of header names.
Setting headers is similar to adding headers. If the request does not have the header configured by the filter, then it
will be added, but unlike adding request headers which will append the value of the header if
the request already contains it, setting a header will cause the value to be replaced by the value configured in the
filter.
Querying headers.example/get should result in a 200 response from the example Gateway and the output from the
example app should indicate that the upstream example app received the header add-header, but the header
remove-header that was sent by curl was removed before the upstream received the request.
In some cases, it could be necessary to modify headers before the proxy performs any sort of processing, routing or tracing. Envoy Gateway supports this functionality using the ClientTrafficPolicy API.
The same Envoy format strings used with RequestHeaderModifier values also apply to early
header modifications, allowing dynamic data to be populated ahead of routing.
A ClientTrafficPolicy resource can be attached to a Gateway resource to configure early header modifications for all its routes. In the following example we will demonstrate how early header modification can be configured.
Querying headers.example/get should result in a 200 response from the example Gateway and the output from the
example app should indicate that the upstream example app received the following headers:
early-added-header contains early (ClientTrafficPolicy) and late (RouteFilter) values
early-set-header contains only early (ClientTrafficPolicy) and late (RouteFilter) values, since the early modification overwritten the client value.
early-removed-header contains only the late (RouteFilter) value, since the early modification deleted the client value.
The HTTPRoute resource can modify the headers of a response before responding it to the downstream service. To learn
more about HTTP routing, refer to the Gateway API documentation.
A ResponseHeaderModifier filter instructs Gateways to modify the headers in responses that match the
rule before responding to the downstream. Note that the ResponseHeaderModifier filter will only modify headers before
the response is returned from Envoy to the downstream client and will not affect request headers forwarding to the
upstream service.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Adding Response Headers
The ResponseHeaderModifier filter can add new headers to a response before it is sent to the upstream. If the response
does not have the header configured by the filter, then that header will be added to the response. If the response
already has the header configured by the filter, then the value of the header in the filter will be appended to the
value of the header in the response.
The HTTPRoute status should indicate that it has been accepted and is bound to the example Gateway.
kubectl get httproute/http-headers -o yaml
Get the Gateway’s address:
exportGATEWAY_HOST=$(kubectl get gateway/eg -o jsonpath='{.status.addresses[0].value}')
Querying headers.example/get should result in a 200 response from the example Gateway and the output from the
example app should indicate that the downstream client received the header add-header with the value: foo
Setting headers is similar to adding headers. If the response does not have the header configured by the filter, then it
will be added, but unlike adding response headers which will append the value of the header
if the response already contains it, setting a header will cause the value to be replaced by the value configured in the
filter.
Querying headers.example/get should result in a 200 response from the example Gateway and the output from the
example app should indicate that the downstream client received the header set-header with the original value value1
replaced by foo.
Headers can be removed from a response by simply supplying a list of header names.
Setting headers is similar to adding headers. If the response does not have the header configured by the filter, then it
will be added, but unlike adding response headers which will append the value of the header
if the response already contains it, setting a header will cause the value to be replaced by the value configured in the
filter.
Querying headers.example/get should result in a 200 response from the example Gateway and the output from the
example app should indicate that the header remove-header that was sent by curl was removed before the upstream
received the response.
In some cases it may be necessary to modify response headers globally. For example, you may want to add a security header (such as Strict-Transport-Security) to all routes. Envoy Gateway supports this functionality using the ClientTrafficPolicy API.
A ClientTrafficPolicy resource can be attached to a Gateway resource to configure late header modification for all its routes. In the following example we will demonstrate how late header modification can be configured.
In some cases you may want to set default headers at the gateway level that can be overridden by backend responses. For example, you may want to add a default Content-Security-Policy header to all responses, but allow specific backends to provide their own policy. The addIfAbsent action adds headers only when they don’t already exist in the response.
Unlike add which appends to existing headers, or set which overwrites them, addIfAbsent is a no-op if the header is already present.
Querying headers.example/get should result in a 200 response from the example Gateway. When the backend does not set these headers, the default values from the ClientTrafficPolicy are used:
The HTTPRoute resource allows users to configure HTTP routing by matching HTTP traffic and forwarding it to
Kubernetes backends. Currently, the only backend supported by Envoy Gateway is a Service resource. This task
shows how to route traffic based on host, header, and path fields and forward the traffic to different Kubernetes
Services. To learn more about HTTP routing, refer to the Gateway API documentation.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
Note: Envoy Gateway is configured by default to manage a GatewayClass with
controllerName: gateway.envoyproxy.io/gatewayclass-controller.
Verification
Check the status of the GatewayClass:
kubectl get gc --selector=example=http-routing
The status should reflect “Accepted=True”, indicating Envoy Gateway is managing the GatewayClass.
A Gateway represents configuration of infrastructure. When a Gateway is created, Envoy proxy infrastructure is
provisioned or configured by Envoy Gateway. The gatewayClassName defines the name of a GatewayClass used by this
Gateway. Check the status of the Gateway:
kubectl get gateways --selector=example=http-routing
The status should reflect “Ready=True”, indicating the Envoy proxy infrastructure has been provisioned. The status also
provides the address of the Gateway. This address is used later to test connectivity to proxied backend
services.
The three HTTPRoute resources create routing rules on the Gateway. In order to receive traffic from a Gateway,
an HTTPRoute must be configured with parentRefs which reference the parent Gateway(s) that it should be attached to.
An HTTPRoute can match against a single set of hostnames. These hostnames are matched before any other matching
within the HTTPRoute takes place. Since example.com, foo.example.com, and bar.example.com are separate hosts with
different routing requirements, each is deployed as its own HTTPRoute - example-route, foo-route, and bar-route.
Check the status of the HTTPRoutes:
kubectl get httproutes --selector=example=http-routing -o yaml
The status for each HTTPRoute should surface “Accepted=True” and a parentRef that references the example Gateway.
The example-route matches any traffic for “example.com” and forwards it to the “example-svc” Service.
Testing the Configuration
Before testing HTTP routing to the example-svc backend, get the Gateway’s address.
exportGATEWAY_HOST=$(kubectl get gateway/example-gateway -o jsonpath='{.status.addresses[0].value}')
A 200 status code should be returned and the body should include "pod": "example-backend-*" indicating the traffic
was routed to the example backend service. If you change the hostname to a hostname not represented in any of the
HTTPRoutes, e.g. “www.example.com”, the HTTP traffic will not be routed and a 404 should be returned.
The foo-route matches any traffic for foo.example.com and applies its routing rules to forward the traffic to the
“foo-svc” Service. Since there is only one path prefix match for /login, only foo.example.com/login/* traffic will
be forwarded. Test HTTP routing to the foo-svc backend.
A 200 status code should be returned and the body should include "pod": "foo-backend-*" indicating the traffic
was routed to the foo backend service. Traffic to any other paths that do not begin with /login will not be matched by
this HTTPRoute. Test this by removing /login from the request.
The HTTP traffic will not be routed and a 404 should be returned.
Similarly, the bar-route HTTPRoute matches traffic for bar.example.com. All traffic for this hostname will be
evaluated against the routing rules. The most specific match will take precedence which means that any traffic with the
env:canary header will be forwarded to bar-svc-canary and if the header is missing or not canary then it’ll be
forwarded to bar-svc. Test HTTP routing to the bar-svc backend.
A 200 status code should be returned and the body should include "pod": "bar-canary-backend-*" indicating the
traffic was routed to the foo backend service.
JWT Claims Based Routing
Users can route to a specific backend by matching on JWT claims.
This can be achieved, by defining a SecurityPolicy with a jwt configuration that does the following
Converts jwt claims to headers, which can be used for header based routing
Sets the recomputeRoute field to true. This is required so that the incoming request matches on a fallback/catch all route where the JWT can be authenticated, the claims from the JWT can be converted to headers, and then the route match can be recomputed to match based on the updated headers.
For this feature to work please make sure
you have a fallback route rule defined, the backend for this route rule can be invalid.
The SecurityPolicy is applied to both the fallback route as well as the route with the claim header matches, to avoid spoofing.
The request should return the pod name, for example bar-backend-6688b8944c-s8htr
Cookie Based Routing
Users can route to a specific backend by matching on HTTP cookies. This is
achieved by defining an
HTTPRouteFilter that specifies
the cookie matching criteria and referencing it in an HTTPRoute rule.
The HTTP traffic will not be routed and a 404 should be returned.
2.2.21 - HTTP Timeouts
The default request timeout is set to 15 seconds in Envoy Proxy.
The HTTPRouteTimeouts resource allows users to configure request timeouts for an HTTPRouteRule.
This task shows you how to configure timeouts.
request: Request specifies the maximum duration for a gateway to respond to an HTTP request.
backendRequest: BackendRequest specifies a timeout for an individual request from the gateway to a backend.
Note: The Request duration must be >= BackendRequest duration
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Verification
backend has the ability to delay responses; we use it as the backend to control response time.
request timeout
We configure the backend to delay responses by 3 seconds, then we set the request timeout to 4 seconds. Envoy Gateway will successfully respond to the request.
* Trying 127.0.0.1:80...
* Connected to 127.0.0.1 (127.0.0.1) port 80
> GET /?delay=3s HTTP/1.1
> Host: timeout.example.com
> User-Agent: curl/8.6.0
> Accept: */*
>< HTTP/1.1 504 Gateway Timeout
< content-length: 24
< content-type: text/plain
< date: Mon, 04 Mar 2024 02:35:03 GMT
<
* Connection #0 to host 127.0.0.1 left intact
upstream request timeout
2.2.22 - HTTP URL Rewrite
HTTPURLRewriteFilter defines a filter that modifies a request during forwarding. At most one of these filters may be
used on a Route rule. This MUST NOT be used on the same Route rule as a HTTPRequestRedirect filter.
The Envoy Gateway HTTPRouteFilter (used for hostname and regex path rewrite) can also be referenced from a GRPCRoute
via an extensionRef filter. For gRPC, a regex :path rewrite operates on the gRPC path, which has the form
/<package>.<Service>/<Method>. See Gateway API support for details.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Rewrite URL Prefix Path
You can configure to rewrite the prefix in the url like below. In this example, any curls to
http://${GATEWAY_HOST}/get/xxx will be rewritten to http://${GATEWAY_HOST}/replace/xxx.
You can see that the X-Envoy-Original-Path is /get/origin/path, but the actual path is /replace/origin/path.
Rewrite URL Full Path
You can configure to rewrite the fullpath in the url like below. In this example, any request sent to
http://${GATEWAY_HOST}/get/origin/path/xxxx will be rewritten to
http://${GATEWAY_HOST}/force/replace/fullpath.
You can see that the X-Envoy-Original-Path is /get/origin/path/extra, but the actual path is
/force/replace/fullpath.
Rewrite URL Path with Regex
In addition to core Gateway-API rewrite options, Envoy Gateway supports extended rewrite options through the HTTPRouteFilter API.
The HTTPRouteFilter API can be configured to use RE2-compatible regex matchers and substitutions to rewrite a portion of the url.
In the example below, requests sent to http://${GATEWAY_HOST}/service/xxx/yyy (where xxx is a single path portion and yyy is one or more path portions)
are rewritten to http://${GATEWAY_HOST}/yyy/instance/xxx. The entire path is matched and rewritten using capture groups.
You can see that the path is rewritten from /service/foo/v1/api, to /v1/api/instance/foo.
Rewrite Host Name
You can configure to rewrite the hostname like below. In this example, any requests sent to
http://${GATEWAY_HOST}/get with --header "Host: path.rewrite.example" will rewrite host into envoygateway.io.
You can see that the X-Forwarded-Host is path.rewrite.example, but the actual host is envoygateway.io.
Rewrite URL Host Name by Header or Backend
In addition to core Gateway-API rewrite options, Envoy Gateway supports extended rewrite options through the HTTPRouteFilter API.
The HTTPRouteFilter API can be configured to rewrite the Host header value to:
The value of a different request header
The DNS name of the backend that the request is routed to
In the following example, the host header is rewritten to the value of the x-custom-host header.
The HTTPRoute status should indicate that it has been accepted and is bound to the example Gateway.
kubectl get httproute/http-filter-header-host-rewrite -o yaml
Querying http://${GATEWAY_HOST}/header and providing a custom host rewrite header x-custom-host should rewrite the
request host header to the value of the x-custom-host header.
You can see that the host is rewritten from host.header.rewrite.example, to the value of the provided
x-custom-host header foo. The original host header is preserved in the X-Forwarded-Host header.
Disabling X-Forwarded-Host Header
By default, when hostname rewriting is configured, Envoy Gateway appends the original Host header value to the
X-Forwarded-Host header on upstream requests. You can disable this behavior by setting appendXForwardedHost to
false in the HTTPRouteFilter API.
When appendXForwardedHost is set to false, the X-Forwarded-Host header will not be added to the upstream
request even though the host is being rewritten. This is useful when the upstream service does not need or should
not receive the original host information.
2.2.23 - HTTP3
This task will help you get started using HTTP3 using EG. EG supports HTTP/3 between the client
and the Gateway, and HTTP/3 between the Gateway and the backend. The two are configured separately
and can be used on their own or together.
This task uses a self-signed CA, so it should be used for testing and demonstration purposes only.
HTTP/3 to Clients
HTTP/3 to clients is enabled with the http3 field of a ClientTrafficPolicy. The Gateway then
listens for QUIC on the HTTPS listener’s port and advertises HTTP/3 to clients with an alt-svc
response header.
Prerequisites
OpenSSL to generate TLS assets.
Installation
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
By default, Envoy Gateway advertises the Gateway listener port in the HTTP/3 alt-svc response header.
If an external load balancer exposes the Gateway on a different port, set advertisedPort to the
external port without changing the listener or Service ports:
HTTP/3 to the backend is enabled with the http3 field of a BackendTrafficPolicy.
Prerequisites
QUIC always runs over TLS, so the backend must already be configured with TLS through a
BackendTLSPolicy or a Backend resource’s spec.tls. When a BackendTrafficPolicy enables
http3 for a route whose backends are not all configured with TLS, or whose backendRefs cannot all
be resolved, HTTP/3 is left off for that route, the rest of the policy still applies, and the policy
reports a Warning condition naming the route. HTTP/3 comes back on its own once the route’s
backends are all resolved and configured with TLS.
HTTP/3 requires a verified backend. A backend with insecureSkipVerify is left off HTTP/3 with
a Warning condition on the policy. Configure the backend’s CA instead, through a
BackendTLSPolicy or the Backend’s tls.caCertificateRefs.
Enabling HTTP/3
Apply a BackendTrafficPolicy with http3 set to the routes whose backends speak HTTP/3. There
are two modes, Auto and Always:
Auto is the default. Envoy uses HTTP/3 only for backends that advertise support for it through an
alt-svc response header. It caches that advertisement, then races a QUIC connection against a TCP
one and uses whichever is established first, so it falls back to HTTP/1.1 or HTTP/2 whenever QUIC is
unavailable. This is the safe choice for backends reached over a network where UDP may be blocked.
Envoy only honors an alt-svc entry whose port is the port it dials the backend on, and that names
no host. For a Service backend that is the Pod IP and targetPort, not the Service port. A backend
that advertises h3=":443" behind a Service that maps port 443 to targetPort 8443 is dialed on
8443, so the advertisement never matches and Auto keeps using TCP. Either have the backend
advertise the port it actually listens on, as in h3=":8443", or give the Service the same port and
targetPort. The same rule applies to a Backend resource: the advertised port must be the
endpoint’s port. The QUIC listener on the backend must also be reachable on that port over UDP.
The backend’s alt-svc header is not forwarded to clients. It names a port on the backend, which a
client would read as a port on the Gateway, so Envoy Gateway strips it after recording it and adds
the Gateway’s own alt-svc when the listener has HTTP/3 enabled. Do not remove alt-svc with an
HTTPRoute ResponseHeaderModifier filter: that runs before the advertisement is recorded, so
Auto mode would never discover the backend’s HTTP/3 support.
Always Mode
Always sends every request over HTTP/3 and never falls back to TCP. Use it only where the backend
is known to speak HTTP/3 and UDP is known to work, since there is no recovery if QUIC fails. Active
health checks are the exception: Envoy sends them over TLS on TCP even in Always mode, so a backend
with an active healthCheck must also accept TCP on the same port, or every endpoint is marked
unhealthy while QUIC traffic still works. Passive health checks observe the QUIC traffic itself and
are unaffected.
Limitations
The EnvoyProxy backendTLS.alpnProtocols setting is not applied to a cluster using HTTP/3. Envoy
offers that list on the QUIC handshake too, where only h3 is valid, so the cluster offers no ALPN
list of its own: QUIC negotiates h3 and the cluster’s TCP connections fall back to h2 and
http/1.1. The policy reports a Warning condition naming the cluster.
http3 cannot be combined with useClientProtocol or proxyProtocol: the first would have Envoy
pick the upstream protocol from the downstream request, and PROXY protocol is a TCP preamble with
no QUIC equivalent. A policy that sets both is rejected at admission. HTTP/3 is also left off, with
the same Warning condition, for backends that declare an HTTP/2 or gRPC appProtocol, since
those ask for a protocol HTTP/3 cannot provide.
2.2.24 - HTTPRoute Request Mirroring
The HTTPRoute resource allows one or more backendRefs to be provided. Requests will be routed to these upstreams. It is possible to divide the traffic between these backends using Traffic Splitting, but it is also possible to mirror requests to another Service instead. Request mirroring is accomplished using Gateway API’s HTTPRequestMirrorFilter on the HTTPRoute.
When requests are made to a HTTPRoute that uses a HTTPRequestMirrorFilter, the response will never come from the backendRef defined in the filter. Responses from the mirror backendRef are always ignored.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Mirroring the Traffic
Next, create a new Deployment and Service to mirror requests to. The following example will use
a second instance of the application deployed in the quickstart.
Then create an HTTPRoute that uses a HTTPRequestMirrorFilter to send requests to the original
service from the quickstart, and mirror request to the service that was just deployed.
The HTTPRoute status should indicate that it has been accepted and is bound to the example Gateway.
kubectl get httproute/http-mirror -o yaml
Get the Gateway’s address:
exportGATEWAY_HOST=$(kubectl get gateway/eg -o jsonpath='{.status.addresses[0].value}')
Querying backends.example/get should result in a 200 response from the example Gateway and the output from the
example app should indicate which pod handled the request. There is only one pod in the deployment for the example app
from the quickstart, so it will be the same on all subsequent requests.
Check the logs of the pods and you will see that the original deployment and the new deployment each got a request:
$ kubectl logs deploy/backend && kubectl logs deploy/backend-2
...
Starting server, listening on port 3000(http)Echoing back request made to /get to client (10.42.0.10:41566)Starting server, listening on port 3000(http)Echoing back request made to /get to client (10.42.0.10:45096)
Multiple BackendRefs
When an HTTPRoute has multiple backendRefs and an HTTPRequestMirrorFilter, traffic splitting will still behave the same as it normally would for the main backendRefs while the backendRef of the HTTPRequestMirrorFilter will continue receiving mirrored copies of the incoming requests.
Multiple HTTPRequestMirrorFilters can be configured on the same HTTPRoute rule. Traffic splitting will work as expected, with mirrored requests being directed to backendRefs with HTTPRequestMirrorFilter filter and the actual requests to main backendRefs.
The HTTPRoute resource allows one or more backendRefs to be provided. Requests will be routed to these upstreams
if they match the rules of the HTTPRoute. If an invalid backendRef is configured, then HTTP responses will be returned
with status code 500 for all requests that would have been sent to that backend.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The HTTPRoute status should indicate that it has been accepted and is bound to the example Gateway.
kubectl get httproute/http-headers -o yaml
Get the Gateway’s address:
exportGATEWAY_HOST=$(kubectl get gateway/eg -o jsonpath='{.status.addresses[0].value}')
Querying backends.example/get should result in a 200 response from the example Gateway and the output from the
example app should indicate which pod handled the request. There is only one pod in the deployment for the example app
from the quickstart, so it will be the same on all subsequent requests.
Querying backends.example/get should result in 200 responses from the example Gateway and the output from the
example app that indicates which pod handled the request should switch between the first pod and the second one from the
new deployment on subsequent requests.
If multiple backendRefs are configured and an un-even traffic split between the backends is desired, then the weight
field can be used to control the weight of requests to each backend. If weight is not configured for a backendRef it is
assumed to be 1.
The weight field in a backendRef controls the distribution of the traffic split. The proportion of
requests to a single backendRef is calculated by dividing its weight by the sum of all backendRef weights in the
HTTPRoute. The weight is not a percentage and the sum of all weights does not need to add up to 100.
The HTTPRoute below will configure the gateway to send 80% of the traffic to the backend service, and 20% to the
backend-2 service.
backendRefs can be considered invalid for the following reasons:
The group field is configured to something other than "". Currently, only the core API group (specified by
omitting the group field or setting it to an empty string) is supported
The kind field is configured to anything other than Service. Envoy Gateway currently only supports Kubernetes
Service backendRefs
The backendRef configures a service with a namespace not permitted by any existing ReferenceGrants
The port field is not configured or is configured to a port that does not exist on the Service
The named Service configured by the backendRef cannot be found
Modifying the above example to make the backend-2 backendRef invalid by using a port that does not exist on the Service
will result in 80% of the traffic being sent to the backend service, and 20% of the traffic receiving an HTTP response
with status code 500.
Querying backends.example/get should result in 200 responses 80% of the time, and 500 responses 20% of the time.
$ curl -vvv --header "Host: backends.example""http://${GATEWAY_HOST}/get"> GET /get HTTP/1.1
> Host: backends.example
> User-Agent: curl/7.81.0
> Accept: */*
>* Mark bundle as not supporting multiuse
< HTTP/1.1 500 Internal Server Error
< server: envoy
< content-length: 0
<
2.2.26 - ListenerSets
ListenerSet is a Gateway API resource that defines listeners in a separate object and attaches them to a Gateway. Instead of declaring every port, hostname, and TLS certificate on the Gateway itself, teams can manage their own listeners in their own namespaces, while all listeners are served by the same Envoy Proxy fleet.
ListenerSets are useful when:
You need more than the 64 listeners allowed on a single Gateway.
A platform team owns the Gateway, and application teams need to self-service their own ports, hostnames, and
TLS certificates without touching the Gateway.
Listeners and their TLS secrets must live in a different namespace than the Gateway.
Envoy Gateway supports attaching HTTPRoute (HTTP/HTTPS), GRPCRoute, TLSRoute, TCPRoute, and UDPRoute to ListenerSet
listeners. Envoy Gateway policies, including ClientTrafficPolicy, SecurityPolicy, BackendTrafficPolicy, and
EnvoyExtensionPolicy, can target a ListenerSet, or a single listener in it via sectionName.
The ListenerSet CRD ships with the Gateway API CRDs installed by Envoy Gateway. No Envoy Gateway configuration is
required: the resource is reconciled whenever the CRD is present in the cluster.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Configuration
A Gateway must explicitly opt in to ListenerSet attachment through spec.allowedListeners. By default, no ListenerSets are allowed. Update the Gateway from the Quickstart to accept ListenerSets from the same namespace:
allowedListeners.namespaces.from also supports All and Selector to accept ListenerSets from any namespace or
from namespaces matching a label selector, which is the typical setup when application teams manage ListenerSets in
their own namespaces.
Create a ListenerSet that adds an extra HTTP listener on port 8080, and an HTTPRoute that attaches to it by
referencing the ListenerSet as its parent:
HTTPS listeners work the same way: a ListenerSet listener can terminate TLS with certificateRefs pointing at
Secrets in the ListenerSet’s namespace, so application teams manage their own certificates.
Listener conflicts
Listeners across the Gateway and its ListenerSets must not clash on port, protocol, and hostname. When they do,
the Gateway’s own listeners take precedence and conflicted listeners are rejected, reporting Conflicted: True
in their status. See the upstream listener conflicts guide for the full rules.
Comparison with Merged Gateways
Before ListenerSet existed in the Gateway API, Envoy Gateway offered the custom Merged Gateways deployment
mode (mergeGateways in the EnvoyProxy resource), which collapses the listeners of all Gateways under a
GatewayClass onto a single Envoy Proxy fleet. Both features let multiple teams share one data plane, but they work
differently:
ListenerSet
Merged Gateways (mergeGateways)
API
Gateway API-native resource, portable across implementations
Envoy Gateway-specific EnvoyProxy setting
Unit of sharing
One Gateway shares its infrastructure with many ListenerSets
All Gateways under one GatewayClass share one Envoy fleet
Opt-in
Per Gateway, via spec.allowedListeners
Per GatewayClass, via mergeGateways: true in EnvoyProxy
Delegation model
Gateway owner controls which namespaces may attach listeners
Any Gateway under the GatewayClass is merged, no per-Gateway consent
Listener limit
64 per resource, scale by adding ListenerSets to one Gateway
64 per resource, scale by adding Gateways under the GatewayClass
Status reporting
Per-ListenerSet status, plus attachedListenerSets on the Gateway
Each Gateway reports status for its own listeners only
Policy attachment
Policies can target a ListenerSet or its individual listeners
Policies target each Gateway separately
For new deployments, prefer ListenerSet: it is the upstream Gateway API design for this use case, and it gives the Gateway owner explicit control over who may attach listeners.
Moving to ListenerSet requires converting Gateways into ListenerSets and rewriting the parentRefs of every route.
See issue 1230 for the original motivation behind mergeGateways.
2.2.27 - Load Balancing
Envoy load balancing is a way of distributing traffic between multiple hosts within a single upstream cluster
in order to effectively make use of available resources.
Envoy Gateway supports the following load balancing policies:
Round Robin: a simple policy in which each available upstream host is selected in round robin order.
Random: load balancer selects a random available host.
Least Request: load balancer uses different algorithms depending on whether hosts have the same or different weights.
Consistent Hash: load balancer implements consistent hashing to upstream hosts.
Additionally, Envoy Gateway supports Endpoint Override functionality that allows endpoint selection based on headers or metadata, which can be used with any of the above load balancing policies as a fallback.
Envoy Gateway introduces a new CRD called BackendTrafficPolicy that allows the user to describe their desired load balancing polices.
This instantiated resource can be linked to a Gateway, HTTPRoute or GRPCRoute resource. If loadBalancer is not specified in BackendTrafficPolicy, the default load balancing policy is Least Request.
Prerequisites
Install Envoy Gateway
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
As a result, you can see all available upstream hosts receive traffics evenly.
kubectl get pods -l app=backend --no-headers -o custom-columns=":metadata.name"|whileread -r pod;doecho"$pod: received $(($(kubectl logs $pod| wc -l)-2)) requests";done
backend-69fcff487f-2gfp7: received 26 requests
backend-69fcff487f-69g8c: received 25 requests
backend-69fcff487f-bqwpr: received 24 requests
backend-69fcff487f-kbn8l: received 25 requests
You should note that this results may vary, the output here is for reference purpose only.
Random
This example will create a Load Balancer with Random policy via BackendTrafficPolicy.
As a result, you can see all available upstream hosts receive traffics randomly.
kubectl get pods -l app=backend --no-headers -o custom-columns=":metadata.name"|whileread -r pod;doecho"$pod: received $(($(kubectl logs $pod| wc -l)-2)) requests";done
backend-69fcff487f-bf6lm: received 246 requests
backend-69fcff487f-gwmqk: received 256 requests
backend-69fcff487f-mzngr: received 230 requests
backend-69fcff487f-xghqq: received 268 requests
You should note that this results may vary, the output here is for reference purpose only.
Least Request
This example will create a Load Balancer with Least Request policy via BackendTrafficPolicy.
As a result, you can see all available upstream hosts receive traffics randomly,
and host backend-69fcff487f-6l2pw receives fewer requests than others.
kubectl get pods -l app=backend --no-headers -o custom-columns=":metadata.name"|whileread -r pod;doecho"$pod: received $(($(kubectl logs $pod| wc -l)-2)) requests";done
backend-69fcff487f-59hvs: received 24 requests
backend-69fcff487f-6l2pw: received 19 requests
backend-69fcff487f-ktsx4: received 30 requests
backend-69fcff487f-nqxc7: received 27 requests
If you send one more requests to the ${GATEWAY_HOST}/least, you can tell that host backend-69fcff487f-6l2pw is very likely
to get the attention of load balancer and receive this request.
backend-69fcff487f-59hvs: received 24 requests
backend-69fcff487f-6l2pw: received 20 requests
backend-69fcff487f-ktsx4: received 30 requests
backend-69fcff487f-nqxc7: received 27 requests
You should note that this results may vary, the output here is for reference purpose only.
Consistent Hash
This example will create a Load Balancer with Consistent Hash policy via BackendTrafficPolicy.
The underlying consistent hash algorithm that Envoy Gateway utilise is Maglev, and it can derive hash from following aspects:
SourceIP
Header
Cookie
They are also the supported value as consistent hash type.
Source IP
This example will create a Load Balancer with Source IP based Consistent Hash policy.
As a result, you can see all traffics are routed to only one upstream host, since the client that send requests
has the same source IP.
kubectl get pods -l app=backend --no-headers -o custom-columns=":metadata.name"|whileread -r pod;doecho"$pod: received $(($(kubectl logs $pod| wc -l)-2)) requests";done
backend-69fcff487f-grzkj: received 0 requests
backend-69fcff487f-n4d8w: received 100 requests
backend-69fcff487f-tb7zx: received 0 requests
backend-69fcff487f-wbzpg: received 0 requests
You can try different client to send out these requests, the upstream host that receives traffics may vary.
Header
This example will create a Load Balancer with Header based Consistent Hash policy.
As a result, you can see all traffics are routed to only one upstream host, since the header of all requests are the same.
kubectl get pods -l app=backend --no-headers -o custom-columns=":metadata.name"|whileread -r pod;doecho"$pod: received $(($(kubectl logs $pod| wc -l)-2)) requests";done
backend-69fcff487f-dvt9r: received 0 requests
backend-69fcff487f-f8qdl: received 100 requests
backend-69fcff487f-gnpm4: received 0 requests
backend-69fcff487f-t2pgm: received 0 requests
You can try to add different header to these requests, and the upstream host that receives traffics may vary.
The following output happens when you use hey to send another 100 requests with header FooBar: 5.6.7.8.
backend-69fcff487f-dvt9r: received 0 requests
backend-69fcff487f-f8qdl: received 100 requests
backend-69fcff487f-gnpm4: received 100 requests
backend-69fcff487f-t2pgm: received 0 requests
Cookie
This example will create a Load Balancer with Cookie based Consistent Hash policy.
By sending 10 request with curl to the ${GATEWAY_HOST}/cookie, you can see that all requests got routed to only
one upstream host, since they have same cookie setting.
for i in {1..10};do curl -I --header "Host: www.example.com" --cookie "FooBar=1.2.3.4" http://${GATEWAY_HOST}/cookie ; sleep 1;done
kubectl get pods -l app=backend --no-headers -o custom-columns=":metadata.name"|whileread -r pod;doecho"$pod: received $(($(kubectl logs $pod| wc -l)-2)) requests";done
backend-69fcff487f-5dxz9: received 0 requests
backend-69fcff487f-gpvl2: received 0 requests
backend-69fcff487f-pglgv: received 10 requests
backend-69fcff487f-qxr74: received 0 requests
You can try to set different cookie to these requests, the upstream host that receives traffics may vary.
The following output happens when you use curl to send another 10 requests with cookie FooBar: 5.6.7.8.
backend-69fcff487f-dvt9r: received 0 requests
backend-69fcff487f-f8qdl: received 0 requests
backend-69fcff487f-gnpm4: received 10 requests
backend-69fcff487f-t2pgm: received 10 requests
If the cookie has not been set in one request, Envoy Gateway will auto-generate a cookie for this request
according to the ttl and attributes field.
In this example, the following cookie will be generated (see set-cookie header in response) if sending a request without cookie:
First, get one of the backend pod IPs to use as the override endpoint:
BACKEND_POD_IP=$(kubectl get pods -l app=backend -o jsonpath='{.items[0].status.podIP}')echo"Backend Pod IP: $BACKEND_POD_IP"
Test with a valid pod IP in the header - all requests should go to the specific pod:
for i in {1..10};do curl -s -H "Host: www.example.com" -H "x-custom-host: $BACKEND_POD_IP:3000"\
http://${GATEWAY_HOST}/endpoint-override-header | jq -r '.pod'done
All requests should return the same pod name, demonstrating that the endpoint override is working.
Test with an invalid IP in the header - requests should fall back to round robin:
for i in {1..10};do curl -s -H "Host: www.example.com" -H "x-custom-host: 192.168.1.100:3000"\
http://${GATEWAY_HOST}/endpoint-override-header | jq -r '.pod'done
You should see requests distributed across different pods using the round robin fallback policy.
2.2.28 - Local Rate Limit
Rate limit is a feature that allows the user to limit the number of incoming requests to a predefined value based on attributes within the traffic flow.
Here are some reasons why you may want to implement Rate limits
To prevent malicious activity such as DDoS attacks.
To prevent applications and its resources (such as a database) from getting overloaded.
Local rate limiting applies rate limits to the traffic flowing through a single instance of Envoy proxy. This means
that if the data plane has 2 replicas of Envoy running, and the rate limit is 10 requests/second, each replica will allow
10 requests/second. This is in contrast to Global Rate Limiting which applies rate limits to the traffic flowing through
all instances of Envoy proxy.
Envoy Gateway introduces a new CRD called BackendTrafficPolicy that allows the user to describe their rate limit intent.
This instantiated resource can be linked to a Gateway, HTTPRoute or GRPCRoute resource.
Note: Limit is applied per route. Even if a BackendTrafficPolicy targets a gateway, each route in that gateway
still has a separate rate limit bucket. For example, if a gateway has 2 routes, and the limit is 100r/s, then each route
has its own 100r/s rate limit bucket.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Rate Limit Specific User
Here is an example of a rate limit implemented by the application developer to limit a specific user by matching on a custom x-user-id header
with a value set to one.
The HTTPRoute status should indicate that it has been accepted and is bound to the example Gateway.
kubectl get httproute/http-ratelimit -o yaml
Get the Gateway’s address:
exportGATEWAY_HOST=$(kubectl get gateway/eg -o jsonpath='{.status.addresses[0].value}')
Let’s query ratelimit.example/get 4 times. We should receive a 200 response from the example Gateway for the first 3 requests
and then receive a 429 status code for the 4th request since the limit is set at 3 requests/Hour for the request which contains the header x-user-id
and value one.
for i in {1..4};do curl -I --header "Host: ratelimit.example" --header "x-user-id: one" http://${GATEWAY_HOST}/get ; sleep 1;done
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:31 GMT
content-length: 460
x-envoy-upstream-service-time: 4
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:32 GMT
content-length: 460
x-envoy-upstream-service-time: 2
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:33 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 429 Too Many Requests
x-envoy-ratelimited: true
date: Wed, 08 Feb 2023 02:33:34 GMT
server: envoy
transfer-encoding: chunked
You should be able to send requests with the x-user-id header and a different value and receive successful responses from the server.
for i in {1..4};do curl -I --header "Host: ratelimit.example" --header "x-user-id: two" http://${GATEWAY_HOST}/get ; sleep 1;done
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:34:36 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:34:37 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:34:38 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:34:39 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
Rate Limit Specific User Unless within Test Org
Here is an example of a rate limit implemented by the application developer to limit a specific user by matching on a custom x-user-id header
with a value set to one. But the user must not be limited if logging in within Test org, determined by custom header x-org-id set to test.
The HTTPRoute status should indicate that it has been accepted and is bound to the example Gateway.
kubectl get httproute/http-ratelimit -o yaml
Get the Gateway’s address:
exportGATEWAY_HOST=$(kubectl get gateway/eg -o jsonpath='{.status.addresses[0].value}')
Let’s query ratelimit.example/get 4 times with x-user-id set to one and x-org-id set to org1. We should receive a 200 response from the example Gateway for the first 3 requests and the last request should be rate limited.
for i in {1..4};do curl -I --header "Host: ratelimit.example" --header "x-user-id: one" --header "x-org-id: org1" http://${GATEWAY_HOST}/get ; sleep 1;done
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:31 GMT
content-length: 460
x-envoy-upstream-service-time: 4
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:32 GMT
content-length: 460
x-envoy-upstream-service-time: 2
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:33 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 429 Too Many Requests
x-envoy-ratelimited: true
date: Wed, 08 Feb 2023 02:33:34 GMT
server: envoy
transfer-encoding: chunked
Let’s query ratelimit.example/get 4 times with x-user-id set to one and x-org-id set to test. We should receive a 200 response from the example Gateway for all the 4 requests, unlike previous example where the last request was rate limited.
for i in {1..4};do curl -I --header "Host: ratelimit.example" --header "x-user-id: one" --header "x-org-id: test" http://${GATEWAY_HOST}/get ; sleep 1;done
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:31 GMT
content-length: 460
x-envoy-upstream-service-time: 4
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:32 GMT
content-length: 460
x-envoy-upstream-service-time: 2
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:33 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:33 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
Rate Limit All Requests
This example shows you how to rate limit all requests matching the HTTPRoute rule at 3 requests/Hour by leaving the clientSelectors field unset.
For a single selector of type Distinct, local rate limiting keeps a separate token bucket per distinct matched value, subject to the cache capacity described below. A sourceCIDR selector distinguishes the detected client IP addresses within the CIDR, and a header selector distinguishes header values.
Envoy keys a sourceCIDR selector on the client address it detects. When clients reach Envoy through trusted proxies that pass their addresses in X-Forwarded-For, first configure clientIPDetection in a ClientTrafficPolicy targeting the Gateway for that proxy chain; see Configure Client IP Detection. Otherwise the directly connected peer’s address is used, and every client behind the same proxy shares one bucket.
This example limits each client IP to 10 requests/Minute. The 0.0.0.0/0 CIDR only covers IPv4 clients; add a second rule with ::/0 to limit IPv6 clients too.
Each Envoy proxy keeps these buckets in its own memory, in a bounded least recently used cache per rule with a Distinct selector on each route. The cache holds 10,000 entries. A client whose requests reach different proxies gets a separate budget on each, and every bucket starts full again when the proxy restarts. When a new value does not fit in the cache, the least recently used entry is evicted; if that value appears again, its bucket starts full, so cache churn can let a value exceed its configured rate. Use Global Rate Limiting when the limit must be shared across proxies.
Rate Limit Based on Path
This example shows you how to rate limit requests based on the request path. In this case, we want to limit requests to /api/users to 3 requests/Hour.
Let’s test the path-based rate limit by querying /api/users and /api/products. The rate limit of 3 requests/Hour is only applied to /api/users:
# First, test the rate-limited path /api/users - 4 requests (4th should be rate limited)for i in {1..4};do curl -I --header "Host: ratelimit.example" http://${GATEWAY_HOST}/api/users ; sleep 1;done# Now test a different path that should not be rate limitedfor i in {1..4};do curl -I --header "Host: ratelimit.example" http://${GATEWAY_HOST}/api/products ; sleep 1;done
# Requests to /api/users (rate limited after 3 requests)HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:31 GMT
content-length: 460
x-envoy-upstream-service-time: 4
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:32 GMT
content-length: 460
x-envoy-upstream-service-time: 2
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:33 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 429 Too Many Requests
x-envoy-ratelimited: true
date: Wed, 08 Feb 2023 02:33:34 GMT
server: envoy
transfer-encoding: chunked
# Requests to /api/products (not rate limited)HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:35 GMT
content-length: 460
x-envoy-upstream-service-time: 4
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:36 GMT
content-length: 460
x-envoy-upstream-service-time: 2
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:37 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:38 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
As you can see, requests to /api/users are rate limited after the 3rd request (returning 429), while all requests to /api/products succeed without any rate limit.
Rate Limit Based on HTTP Method
This example shows you how to rate limit requests based on the HTTP method. In this case, we want to limit POST requests to 3 requests/Hour.
Let’s test the method-based rate limit. POST requests are limited to 3 requests/Hour, while GET requests are not limited:
# Send 4 POST requests - the 4th one should be rate limitedfor i in {1..4};do curl -X POST -I --header "Host: ratelimit.example" http://${GATEWAY_HOST}/api/data ; sleep 1;done# GET requests should not be rate limitedfor i in {1..4};do curl -X GET -I --header "Host: ratelimit.example" http://${GATEWAY_HOST}/api/data ; sleep 1;done
# POST requests (rate limited after 3 requests)HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:31 GMT
content-length: 460
x-envoy-upstream-service-time: 4
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:32 GMT
content-length: 460
x-envoy-upstream-service-time: 2
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:33 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 429 Too Many Requests
x-envoy-ratelimited: true
date: Wed, 08 Feb 2023 02:33:34 GMT
server: envoy
transfer-encoding: chunked
# GET requests (not rate limited)HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:35 GMT
content-length: 460
x-envoy-upstream-service-time: 4
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:36 GMT
content-length: 460
x-envoy-upstream-service-time: 2
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:37 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
HTTP/1.1 200 OK
content-type: application/json
x-content-type-options: nosniff
date: Wed, 08 Feb 2023 02:33:38 GMT
content-length: 460
x-envoy-upstream-service-time: 0
server: envoy
As you can see, POST requests are rate limited after the 3rd request (returning 429), while GET requests to the same path are not rate limited.
2.2.29 - Multicluster Service Routing
The Multicluster Service API ServiceImport object can be used as part of the GatewayAPI backendRef for configuring routes. For more information about multicluster service API follow sig documentation.
We will use Submariner project for setting up the multicluster environment for exporting the service to be routed from peer clusters.
Setting KIND clusters and installing Submariner.
We will be using KIND clusters to demonstrate this example.
git clone https://github.com/submariner-io/submariner-operator
cd submariner-operator
make clusters
Note: remain in submariner-operator directory for the rest of the steps in this section
Envoy Gateway introduces a new CRD called BackendTrafficPolicy that allows the user to control how much of a request body Envoy may
buffer, and whether requests are fully buffered before being forwarded upstream. This instantiated resource can be linked to a Gateway,
or HTTPRoute.
If the target of the BackendTrafficPolicy is a Gateway, the configuration will be applied to all xRoutes under that Gateway.
Configuring requestBuffer requires specifying a size limit. Any request whose buffered body is larger than the limit will stop the
buffering and return a HTTP 413 Content Too Large response. The requestBuffer.mode field selects how that limit is enforced:
BufferAndLimit (the default) stops filter iteration and waits for a fully buffered complete request before forwarding it upstream, using the
Envoy buffer filter. This is useful in several situations, including protecting applications from having to deal with partial requests
and high network latency.
LimitOnly only raises the request body buffer limit for the route, without enabling full request buffering. Use it when a filter later
in the chain — such as ext_proc, Lua, or WASM — buffers the request body and the default buffer limit is too small.
Warning: BufferAndLimit requires Envoy to fully receive the request before forwarding it upstream. This does not work with streaming or
upgrade-based traffic such as gRPC streaming and WebSocket. Using BufferAndLimit for those routes can cause requests to hang indefinitely
because the request may never be forwarded upstream. Use full request buffering only on non-streaming HTTP request flows, or use
LimitOnly instead, which is compatible with streaming and protocol upgrades.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
Save and apply the following resources to your cluster:
---apiVersion:gateway.envoyproxy.io/v1alpha1kind:BackendTrafficPolicymetadata:name:request-bufferspec:targetRefs:- group:gateway.networking.k8s.iokind:HTTPRoutename:foorequestBuffer:limit:4# Supports SI units e.g. 4Ki, 1Mi---apiVersion:gateway.networking.k8s.io/v1kind:HTTPRoutemetadata:name:foospec:parentRefs:- name:eghostnames:- "www.example.com"rules:- backendRefs:- group:""kind:Servicename:backendport:3000weight:1matches:- path:type:PathPrefixvalue:/foo
A HTTPRoute resource is created for the /foo path prefix. The request-buffer BackendTrafficPolicy has been created and targeted HTTPRoute foo to enable request buffering. A small buffer limit of 4 bytes is purposely chosen to make testing easier.
Verify the HTTPRoute configuration and status:
kubectl get httproute/foo -o yaml
Verify the BackendTrafficPolicy configuration:
kubectl get backendtrafficpolicy/request-buffer -o yaml
Testing
Ensure the GATEWAY_HOST environment variable from the Quickstart is set. If not, follow the
Quickstart instructions to set the variable.
echo$GATEWAY_HOST
HTTPRoute
We will try sending a request with an empty json object that is less than the buffer limit of 4 bytes
We will now see that sending a payload of {"key": "value"} which is larger than the request buffer limit of 4 bytes returns a
HTTP 413 Payload Too Large response
Payload Too Large
Status Code: 413
Raising the Buffer Limit Without Full Buffering
Set mode: LimitOnly to raise the request body buffer limit for a route without buffering the whole request in the gateway. The Envoy
buffer filter is not inserted in this mode, so the route stays compatible with streaming and protocol upgrades. The limit is still enforced,
but only against whatever a filter later in the chain — such as ext_proc, Lua, or WASM — actually buffers.
Now send the same payload that was rejected above. Nothing in the filter chain buffers the request body, so the request is streamed
upstream and succeeds even though it is larger than the 4 byte limit:
This limit is independent of the connection buffer limits configured through ClientTrafficPolicy and BackendTrafficPolicy. The
connection buffer limits control downstream and upstream connection read/write buffering and back pressure, while requestBuffer.limit
sets the maximum size of an individual request body that Envoy may buffer for HTTP processing. For HTTP/1, connection buffer limits can
still affect how request body data is read and buffered, so configure them large enough for the request body buffering you expect to allow.
Clean-Up
Follow the steps from the Quickstart to uninstall Envoy Gateway and the example manifest.
Response Compression allows you to compress the response from the backend before sending it to the client. This can be useful for scenarios where the backend sends large responses that can be compressed to reduce the network bandwidth. However, this comes with a trade-off of increased CPU usage on the Envoy side to compress the response.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Testing Response Compression
You can enable compression by specifying the compression types in the BackendTrafficPolicy resource using the compressor field.
Multiple compression types can be defined within the resource, allowing Envoy Gateway to choose the most appropriate option based on the Accept-Encoding header provided by the client.
Envoy Gateway currently supports Brotli, Gzip, and Zstd compression algorithms. Additional compression algorithms may be supported in the future.
Note
The compression field is deprecated. Use the compressor field instead, which provides more granular control over compression configuration.
When a response is compressed, Envoy strips strong ETag headers by default (weak ETags, prefixed with W/, are preserved). This is because compression changes the response body, so the original entity tag no longer identifies the representation that reaches the client.
See the upstream Envoy compressor filter documentation for full details of the ETag handling options (disable_on_etag_header, weaken_etag_on_compress).
Configuring Minimum Content Length
You can configure the minimum response size for compression using the minContentLength field. Responses smaller than this threshold will not be compressed. This can reduce CPU overhead for small responses.
The minimum allowed value is 30 bytes (enforced by Envoy Proxy). If not specified, Envoy’s default of 30 bytes is used.
To specify the desired compression type, include the Accept-Encoding header in requests sent to the Envoy Gateway. The quality value (q) in the Accept-Encoding header determines the priority of each compression type. Envoy Gateway will select the compression type with the highest q value that matches a type configured in the BackendTrafficPolicy resource.
Response Override allows you to override the response from the backend with a custom one. This can be useful for scenarios such as returning a custom 404 page when the requested resource is not found, a custom 500 error message when the backend is failing, or redirecting the client when the backend returns a 403 Forbidden. When using redirect, Envoy applies it internally: Envoy follows the redirect to the new URL, obtains the response from that URL, and sends that response to the client.
Each rule accepts an optional source field that controls which responses the rule applies to:
All (default) — overrides both Envoy-generated responses (e.g. auth failures, rate-limit rejections) and upstream responses with the matched status code.
Backend — overrides only responses from the upstream backend.
Local — overrides only responses generated by Envoy itself (e.g. a 401 from JWT authentication, a 429 from rate limiting). This is useful when you want to customise error messages from Envoy policies without affecting legitimate upstream responses that happen to share the same status code.
Installation
Follow the steps from the Quickstart to install Envoy Gateway and the example manifest.
Before proceeding, you should be able to query the example backend using HTTP.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Testing Response Override
cat <<EOF | kubectl apply -f -
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: BackendTrafficPolicy
metadata:
name: response-override
spec:
targetRefs:
- group: gateway.networking.k8s.io
kind: HTTPRoute
name: backend
responseOverride:
- match:
statusCodes:
- type: Value
value: 404
response:
contentType: text/plain
body:
type: Inline
inline: "Oops! Your request is not found."
- match:
statusCodes:
- type: Value
value: 403 # status from backend when envoy will execute the redirect
redirect:
statusCode: 302 # status envoy should respond to client
scheme: https
hostname: www.example.com
path:
type: ReplaceFullPath
replaceFullPath: "/get"
- match:
statusCodes:
- type: Value
value: 500
- type: Range
range:
start: 501
end: 511
response:
contentType: application/json
body:
type: ValueRef
valueRef:
group: ""
kind: ConfigMap
name: response-override-config
---
apiVersion: v1
kind: ConfigMap
metadata:
name: response-override-config
data:
response.body: '{"error": "Internal Server Error"}'
EOF
Save and apply the following resource to your cluster:
---apiVersion:gateway.envoyproxy.io/v1alpha1kind:BackendTrafficPolicymetadata:name:response-overridespec:targetRefs:- group:gateway.networking.k8s.iokind:HTTPRoutename:backendresponseOverride:- match:statusCodes:- type:Valuevalue:404response:contentType:text/plainbody:type:Inlineinline:"Oops! Your request is not found."- match:statusCodes:- type:Valuevalue:403# status from backend when envoy will execute the redirectredirect:statusCode:302# status envoy should respond to clientscheme:httpshostname:www.example.compath:type:ReplaceFullPathreplaceFullPath:"/get"- match:statusCodes:- type:Valuevalue:500- type:Rangerange:start:501end:511response:contentType:application/jsonbody:type:ValueRefvalueRef:group:""kind:ConfigMapname:response-override-config---apiVersion:v1kind:ConfigMapmetadata:name:response-override-configdata:response.body:'{"error": "Internal Server Error"}'
* Trying 127.0.0.1:80...
* Connected to 172.18.0.200 (172.18.0.200) port 80
> GET /status/500 HTTP/1.1
> Host: www.example.com
> User-Agent: curl/8.5.0
> Accept: */*
>< HTTP/1.1 500 Internal Server Error
< content-type: application/json
< content-length: 34
< date: Thu, 07 Nov 2024 09:23:02 GMT
<
* Connection #0 to host 172.18.0.200 left intact
{"error": "Internal Server Error"}
Override Only Envoy-Generated Responses
By default, a responseOverride rule matches any response with the given status code, whether it came from the upstream backend or was generated by Envoy itself (e.g. a 401 produced by JWT authentication). Use source: Local to restrict a rule to Envoy-generated responses only, leaving legitimate upstream responses with the same code untouched.
The following example uses the foo HTTPRoute and jwt-example SecurityPolicy from the
JWT Authentication task. Follow that task first, then apply the
BackendTrafficPolicy below to replace Envoy’s default 401 rejection with a structured JSON error.
< HTTP/1.1 401 Unauthorized
< content-type: application/json
< content-length: 67
<
{"error": "Authentication required. Please provide a valid token."}
Now verify that a backend-generated 401 is not overridden. The backend HTTPRoute from the
Prerequisites section routes all paths to the backend, which echoes back whichever
status code is in the URL. Sending a request to /status/401 produces a 401 that originates from the
upstream, not from Envoy, so the source: Local rule on the foo route leaves it untouched:
The body is empty and the content-type is the backend’s own — no custom JSON, confirming that
source: Local only intercepts Envoy-generated responses.
To see the inverse behaviour, change source to Backend. Now the same custom JSON body is applied
to upstream 401s, but Envoy-generated 401s (e.g. from JWT authentication) pass through unchanged.
< HTTP/1.1 401 Unauthorized
< content-type: application/json
< content-length: 67
<
{"error": "Authentication required. Please provide a valid token."}
However, a request to /foo without a JWT still receives Envoy’s own plain-text rejection,
because source: Backend does not intercept Envoy-generated responses:
The body is Envoy’s default message and the content-type is text/plain — no custom JSON,
confirming that source: Backend only intercepts responses from the upstream backend.
Match on Request and Response Headers
In addition to status codes, a responseOverride rule can match on the headers of the original
request (match.requestHeaders) and on the headers of the response being overridden
(match.responseHeaders). Within either list, every entry must match, and when statusCodes,
requestHeaders and responseHeaders are combined, all of the specified criteria must match.
statusCodes is the only list that matches when any of its entries match.
The following policy only overrides a 503 when the request came from a browser client and the
upstream flagged the failure as its own:
Save and apply the following resource to your cluster:
apiVersion:gateway.envoyproxy.io/v1alpha1kind:BackendTrafficPolicymetadata:name:response-override-header-matchspec:targetRefs:- group:gateway.networking.k8s.iokind:Gatewayname:egresponseOverride:- match:statusCodes:- type:Valuevalue:503requestHeaders:- name:X-Client-Typevalue:type:Exactvalue:browserresponseHeaders:- name:X-Error-Typevalue:type:Prefixvalue:upstream-response:contentType:text/htmlbody:type:Inlineinline:"<html><body>The service is temporarily unavailable.</body></html>"
Request headers are not available for every Envoy-generated response, so a rule that matches on
requestHeaders may never fire for some local replies.
Next Steps
To explore all the options for response override, see the
BackendTrafficPolicy API Reference, which describes
the responseOverride field and its nested match, source and response settings.
2.2.33 - Retry
Starting from v1.3, Envoy Gateway supports HTTPRoute Retries(GEP-1731),
this setting in the core Gateway API takes precedence over the BackendTrafficPolicy configuration.
A retry setting specifies the maximum number of times an Envoy proxy attempts to connect to a service if the initial call fails. Retries can enhance service availability and application performance by making sure that calls don’t fail permanently because of transient problems such as a temporarily overloaded service or network. The interval between retries prevents the called service from being overwhelmed with requests.
Envoy Gateway supports the following retry settings:
NumRetries: is the number of retries to be attempted. Defaults to 2.
RetryOn: specifies the retry trigger condition.
PerRetryPolicy: is the retry policy to be applied per retry attempt.
Envoy Gateway introduces a new CRD called BackendTrafficPolicy that allows the user to describe their desired retry settings. This instantiated resource can be linked to a Gateway, HTTPRoute or GRPCRoute resource.
Note: There are distinct circuit breaker counters for each BackendReference in an xRoute rule. Even if a BackendTrafficPolicy targets a Gateway, each BackendReference in that gateway still has separate circuit breaker counter.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
Routing to endpoints outside the Kubernetes cluster where Envoy Gateway and its corresponding Envoy Proxy fleet is
running is a common use case. This can be achieved by:
defining FQDN addresses in a EndpointSlice (covered in this document)
Follow the steps from the Quickstart to install Envoy Gateway and the example manifest.
Before proceeding, you should be able to query the example backend using HTTP.
Session Persistence allows client requests to be consistently routed to the same backend service instance. This is useful in many scenarios, such as when an application needs to maintain state across multiple requests. In Envoy Gateway, session persistence can be enabled by configuring HTTPRoute or GRPCRoute.
Envoy Gateway supports following session persistence types:
Cookie-based Session Persistence: Session persistence is achieved based on specific cookie information in the request.
Header-based Session Persistence: Session persistence is achieved based on specific header information in the request.
Prerequisites
Install Envoy Gateway
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The session cookie is always issued with Path=/, as recommended by GEP-1619,
so it keeps working when the path seen by the client differs from the path matched by the HTTPRoute, for example
when an edge proxy rewrites the request path before it reaches Envoy Gateway.
Because the cookie is sent to every route on the same host, each HTTPRoute rule on a host that enables
cookie-based session persistence must use a distinct sessionName. Rules that share a sessionName overwrite
each other’s cookie, and session persistence stops working for both. If sessionName is omitted, Envoy Gateway
generates a unique cookie name for the rule, so leaving it unset is the safest choice unless the cookie name has
to match an existing one, such as JSESSIONID.
After updating the ConfigMap, you will need to wait the configuration kicks in. You can force the configuration to be reloaded by restarting the envoy-gateway deployment.
TCPRoute provides a way to route TCP requests. When combined with a Gateway listener, it can be used to forward
connections on the port specified by the listener to a set of backends specified by the TCPRoute. To learn more about
HTTP routing, refer to the Gateway API documentation.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Configuration
In this example, we have one Gateway resource and two TCPRoute resources that distribute the traffic with the following
rules:
All TCP streams on port 8088 of the Gateway are forwarded to port 3001 of foo Kubernetes Service.
All TCP streams on port 8089 of the Gateway are forwarded to port 3002 of bar Kubernetes Service.
In this example two TCP listeners will be applied to the Gateway in order to route them to two separate backend
TCPRoutes, note that the protocol set for the listeners on the Gateway is TCP:
In this way each TCPRoute “attaches” itself to a different port on the Gateway so that the foo service
is taking traffic for port 8088 from outside the cluster and bar service takes the port 8089 traffic.
Before testing, please get the tcp-gateway Gateway’s address first:
exportGATEWAY_HOST=$(kubectl get gateway/tcp-gateway -o jsonpath='{.status.addresses[0].value}')
You can try to use nc to test the TCP connections of envoy gateway with different ports, and you can see them succeeded:
You can see that the traffic routing to bar service when sending request to 8089 port.
2.2.37 - UDP Routing
The UDPRoute resource allows users to configure UDP routing by matching UDP traffic and forwarding it to Kubernetes
backends. This task will use CoreDNS example to walk you through the steps required to configure UDPRoute on Envoy
Gateway.
Note: UDPRoute allows Envoy Gateway to operate as a non-transparent proxy between a UDP client and server. The lack
of transparency means that the upstream server will see the source IP and port of the Gateway instead of the client.
For additional information, refer to Envoy’s UDP proxy documentation.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
Checkout the Developer Guide to get involved in the project.
2.2.38 - Zone Aware Routing
EnvoyGateway makes use of Envoy Zone Aware Routing to keep network traffic in the originating zone.
Preferring same-zone traffic between Pods in your cluster can help with reliability, performance (network latency and throughput), or cost.
Zone-aware routing may be enabled in one of two ways:
The zoneAware field supports two modes: preferLocal (prefer same-zone endpoints while maintaining overall balance) and weightedZones (explicit per-zone traffic weights). Not all load balancing policies support both modes:
LB Policy
preferLocal
weightedZones
RoundRobin
✓
✓
LeastRequest
✓
✓
Random
✓
✓
ConsistentHash
✗
✓
BackendUtilization
✗
✓
DynamicModule
✗
✗
Why some combinations are unsupported:
ConsistentHash + preferLocal: Envoy’s consistent hashing policies (Maglev/RingHash) route based on a request hash rather than endpoint locality, so the prefer-local algorithm cannot be layered on top. Use weightedZones to influence traffic distribution across zones while preserving hash-based affinity.
BackendUtilization + preferLocal: Envoy’s wrr_locality extension, which wraps BackendUtilization with locality-weight support, does not implement the prefer-local routing algorithm. Only weightedZones is supported.
DynamicModule + any zone-aware mode: Custom load balancing modules manage their own endpoint selection entirely. Zone-aware routing cannot be layered on top of an opaque third-party algorithm.
preferLocal and weightedZones are mutually exclusive and cannot be set together for any policy.
Prerequisites
The Kubernetes cluster’s nodes must indicate topology information via the topology.kubernetes.io/zonewell-known label.
There must be at least two valid topology zones for scheduling.
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The example below configures similar behavior to Kubernetes Traffic Distribution and forces all traffic to the local zone via the force field instead
of Envoy’s default behavior which prefers routing locally as much as possible while still achieving overall equal request distribution across all endpoints.
cat <<EOF | kubectl apply -f -
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: BackendTrafficPolicy
metadata:
name: zone-aware-routing
spec:
targetRefs:
- group: gateway.networking.k8s.io
kind: HTTPRoute
name: zone-aware-routing
loadBalancer:
type: RoundRobin
zoneAware:
preferLocal: # Enables Envoy to prefer local zone endpoints while maintaining overall traffic balance across zones
minEndpointsThreshold: 1 # Zone-aware routing is disabled if total number of endpoints is less than this threshold
force: # Forces all traffic to stay within the local zone, regardless of upstream endpoint distribution between zones
minEndpointsInZoneThreshold: 1 # If fewer local endpoints exist than this threshold, fallback to standard zone-aware routing behavior
EOF
Save and apply the following resource to your cluster:
---apiVersion:gateway.envoyproxy.io/v1alpha1kind:BackendTrafficPolicymetadata:name:zone-aware-routingspec:targetRefs:- group:gateway.networking.k8s.iokind:HTTPRoutename:zone-aware-routingloadBalancer:type:RoundRobinzoneAware:preferLocal:# Enables Envoy to prefer local zone endpoints while maintaining overall traffic balance across zonesminEndpointsThreshold:1# Zone-aware routing is disabled if total number of endpoints is less than this thresholdforce:# Forces all traffic to stay within the local zone, regardless of upstream endpoint distribution between zonesminEndpointsInZoneThreshold:1# If fewer local endpoints exist than this threshold, fallback to standard zone-aware routing behavior
WeightedZones
weightedZones distributes traffic across zones proportionally according to explicit weights. Zones not listed receive a default weight of 1.
This mode is supported by RoundRobin, LeastRequest, Random, ConsistentHash, and BackendUtilization.
The example below routes 70% of traffic to us-east-1a and 30% to us-east-1b using BackendUtilization, which combines ORCA-based backend load metrics with locality weighting via Envoy’s wrr_locality extension.
Next apply the example manifests to create two Deployments and an HTTPRoute. For the test configuration one Deployment
(zone-aware-routing-backend-local) includes affinity for EnvoyProxy Pods to ensure its Pods are scheduled in the same
zone and the second Deployment (zone-aware-routing-backend-nonlocal) uses anti-affinity to ensure its Pods don’t
schedule to the same zone in order to demonstrate functionality.
Ensure that both example Deployments are marked as ready and produces the following output:
kubectl get deployment/zone-aware-routing-backend-local deployment/zone-aware-routing-backend-nonlocal -n default
NAME READY UP-TO-DATE AVAILABLE AGE
zone-aware-routing-backend-local 3/3 33 9m1s
zone-aware-routing-backend-nonlocal 3/3 33 9m1s
An HTTPRoute resource is created for the /zone-aware-routing path prefix along with two example Deployment resources that
are respectively configured with pod affinity/anti-affinity targeting the Envoy Proxy Pods for testing.
We will see the following output. The pod header identifies which backend received the request and should have
a name prefix of zone-aware-routing-backend-local-. We should see this behavior every time and the nonlocal backend should
not receive requests.
2.3.1 - Accelerating TLS Handshakes using Private Key Provider in Envoy
TLS operations can be accelerated or the private key can be protected using specialized hardware. This can be leveraged in Envoy using Envoy Private Key Provider is added to Envoy.
Today, there are two private key providers implemented in Envoy as contrib extensions:
Both of them are used to accelerate the TLS handshake through the hardware capabilities.
This task will walk you through the steps required to configure TLS Termination mode for TCP traffic while also using the Envoy Private Key Provider to accelerate the TLS handshake by leveraging QAT and the HW accelerator available on Intel SPR/EMR Xeon server platforms.
Prerequisites
Install Linux kernel 5.17 or similar
Ensure the node has QAT devices by checking the QAT physical function devices presented. Supported Devices
Verification of the plugin deployment and detection of QAT hardware can be confirmed by examining the resource allocations on the nodes:
kubectl get node -o yaml| grep qat.intel.com
It required the node with 3rd generation Intel Xeon Scalable processor server processors, or later.
For kubernetes Cluster, if not all nodes that support Intel® AVX-512 in Kubernetes cluster, you need to add some labels to divide these two kinds of nodes manually or using NFD.
kubectl get nodes -l feature.node.kubernetes.io/cpu-cpuid.AVX512F,feature.node.kubernetes.io/cpu-cpuid.AVX512DQ,feature.node.kubernetes.io/cpu-cpuid.AVX512BW,feature.node.kubernetes.io/cpu-cpuid.AVX512VBMI2,feature.node.kubernetes.io/cpu-cpuid.AVX512IFMA
Check CPUIDS manually on the node if without using NFD:
Follow the steps from the Quickstart to install Envoy Gateway.
Enable the EnvoyPatchPolicy feature, which will allow us to directly configure the Private Key Provider Envoy Filter, since Envoy Gateway does not directly expose this functionality.
After updating the ConfigMap, you will need to wait the configuration kicks in. You can force the configuration to be reloaded by restarting the envoy-gateway deployment.
Using the envoyproxy image with contrib extensions and add qat resources requesting, ensure the k8s scheduler find out a machine with required resource.
Using the envoyproxy image with contrib extensions and add the node affinity to scheduling the Envoy Gateway pod on the machine with required CPU instructions.
Or using preferredDuringSchedulingIgnoredDuringExecution for best effort scheduling, or not doing any node affinity, just doing the random scheduling. The CryptoMB private key provider supports software fallback if the required CPU instructions aren’t here.
You will see a performance boost after private key provider enabled. For example, you will get results as below.
Without private key provider:
All done43069 calls (plus 10 warmup) 6.966 ms avg, 1435.4 qps
With QAT private key provider, the QPS is over 3 times than without private key provider
All done134746 calls (plus 128 warmup) 28.505 ms avg, 4489.6 qps
With CryptoMB private key provider, the QPS is over 2 times than without private key provider.
All done93983 calls (plus 128 warmup) 40.880 ms avg, 3130.5 qps
2.3.2 - API Key Authentication
This task provides instructions for configuring API Key Authentication.
API Key Authentication verifies whether an incoming request includes a valid API key in the header, parameter, or cookie before routing the request to
a backend service.
Envoy Gateway introduces a new CRD called SecurityPolicy that allows the user to configure Api Key
authentication.
This instantiated resource can be linked to a Gateway, HTTPRoute or GRPCRoute resource.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Configuration
API Key must be stored in a kubernetes secret and referenced in the SecurityPolicy configuration.
The secret is an Opaque secret, with each API key stored under a key corresponding to the client ID.
Important
When API keys are extracted from the Authorization header, the value stored in the Kubernetes
Secret must not include the Bearer prefix.
Envoy Gateway compares the extracted header value directly against the stored secret value.
Authentication scheme prefixes (such as Bearer) are not stripped automatically.
For example:
Non-working configuration
stringData:client1:"Bearer my-api-key"
Working configuration
stringData:client1:"my-api-key"
Clients may still send requests using:
Authorization: Bearer my-api-key
Create an API Key Secret
Create an Opaque Secret containing the client ID and its corresponding API key
Checkout the Developer Guide to get involved in the project.
2.3.3 - Backend Mutual TLS with SPIRE
This task shows how Envoy Gateway can establish mTLS to a backend using SPIFFE identities issued by SPIRE.
Instead of storing certificates in Kubernetes Secrets, Envoy fetches its client certificate and the trust bundle from the
SPIRE Agent at runtime through the Secret Discovery Service (SDS). SPIRE rotates the certificates automatically, and
Envoy picks up the new ones without a restart.
The backend in this task is part of an Istio service mesh that also uses SPIRE as its identity provider. Because the
Gateway and the mesh workloads share the same trust domain, Envoy Gateway can talk to mesh workloads with mTLS
without joining the mesh.
The spiffe-oidc-discovery-provider pod may restart a few times while the SPIRE Agents start up. This is expected,
and the longer --timeout gives it time to recover.
The chart installs:
The SPIRE Agent as a DaemonSet. It serves the Workload API and SDS on a Unix domain socket on every node.
The SPIFFE CSI driver (csi.spiffe.io), which mounts that socket into pods.
A default ClusterSPIFFEID that gives every pod outside the SPIRE namespaces the identity
spiffe://example.org/ns/<namespace>/sa/<service-account>. It has no pod selector, so pods don’t need any label.
The Envoy proxy pods get their identity from this default registration, so you don’t need to register them separately.
If you installed SPIRE with a custom ClusterSPIFFEID that selects pods by label, add that label to the Envoy pods with
spec.provider.kubernetes.envoyDeployment.pod.labels in the EnvoyProxy resource.
To confirm which pods the default registration selects, run:
kubectl get clusterspiffeid spire-server-spire-default -o jsonpath='{.spec}'
Install Istio and the backend
Install Istio with a spire sidecar injection template, so mesh workloads get their certificates from SPIRE instead of
istiod:
The httpbin workload’s SPIFFE ID is spiffe://example.org/ns/spire-sample/sa/httpbin.
Enable SDS Secret references
Envoy Gateway reads SDS settings from Secrets of type gateway.envoyproxy.io/sds. This feature is turned off by
default. To turn it on, set enableSDSSecretRef under extensionApis in the EnvoyGateway configuration.
If you installed Envoy Gateway with Helm, as in the Quickstart, use helm upgrade with
--reuse-values so your other settings stay as they are:
Otherwise, edit the envoy-gateway-config ConfigMap with kubectl edit configmap envoy-gateway-config -n envoy-gateway-system
and add the setting to envoy-gateway.yaml. Keep all of the existing configuration:
After updating the ConfigMap, you will need to wait the configuration kicks in. You can force the configuration to be reloaded by restarting the envoy-gateway deployment.
alpnProtocols: [istio] tells the Istio sidecar on the backend that the incoming connection is Istio mTLS. If you
leave it out, the sidecar only accepts the connection when mTLS is enforced with a STRICTPeerAuthentication.
Route traffic to the backend with mTLS
Create an HTTPRoute to httpbin, and a BackendTLSPolicy that validates the backend’s certificate against the
SPIRE trust bundle and its SPIFFE ID:
Istio also runs Gateway API controllers, so the BackendTLSPolicy status shows extra ancestors from
istio.io/gateway-controller and istio.io/mesh-controller with Accepted=False, because Istio doesn’t support
Secret CA references. You can ignore these. The ancestor from gateway.envoyproxy.io/gatewayclass-controller should
be Accepted=True:
The Istio sidecar on httpbin adds an X-Forwarded-Client-Cert header that describes the client certificate it
received. The URI field shows the SPIFFE ID that SPIRE issued to the Envoy proxy:
The SPIRE CRDs are kept when you uninstall the spire-crds chart, so delete them explicitly.
If you keep Envoy Gateway installed, turn SDS Secret references off again, so that Envoy Gateway stops accepting
gateway.envoyproxy.io/sds Secrets. With Helm:
Otherwise, remove enableSDSSecretRef from the envoy-gateway-config ConfigMap (or set it back to false), leave
the other settings unchanged, and restart Envoy Gateway:
Anyone who can create or reference a gateway.envoyproxy.io/sds Secret can make Envoy request any SDS resource that
the proxy’s SPIFFE identity is allowed to fetch. Turn on enableSDSSecretRef only when the users who can create
these Secrets are trusted. To keep mutually untrusted tenants apart, give them separate Envoy proxy deployments, and
so separate SPIFFE identities. See SDS Certificate References for more on SDS Secret references.
2.3.4 - Backend Mutual TLS: Gateway to Backend
This task demonstrates how mTLS can be achieved between the Gateway and a backend.
This task uses a self-signed CA, so it should be used for testing and demonstration purposes only.
Envoy Gateway supports the Gateway-API defined BackendTLSPolicy to establish TLS. For mTLS, the Gateway must authenticate by presenting a client certificate to the backend.
Prerequisites
OpenSSL to generate TLS assets.
Installation
Follow the steps from the Backend TLS to install Envoy Gateway and configure TLS to the backend server.
TLS Certificates
Generate the client certificate and key used by the Gateway for authentication against the backend.
Create a root certificate and private key to sign the client certificate:
Enforce Client Certificate Authentication on the backend
Patch the existing quickstart backend to enforce Client Certificate Authentication. The patch will mount the server certificate and key required for TLS, and the CA certificate into the backend as volumes.
When multiple backends require distinct client certificates, configure each one using a dedicated Backend resource that includes its own client certificate reference.
TLS settings defined in the Backend resource take precedence over the defaults set in EnvoyProxy.backendTLS.
Before creating Backend resources, make sure the Backend API is enabled in the Envoy Gateway configuration (see Backend Routing for full details). If it is not already enabled, update the envoy-gateway-config ConfigMap as shown below:
After updating the ConfigMap, you will need to wait the configuration kicks in. You can force the configuration to be reloaded by restarting the envoy-gateway deployment.
Inspect the output and see that the response contains the details of the TLS handshake between Envoy and the backend.
The response now contains a “peerCertificates” attribute that reflects the client certificate used by the Gateway to establish mTLS with the backend.
This task demonstrates how TLS can be achieved between the Gateway and a backend.
This task uses a self-signed CA, so it should be used for testing and demonstration purposes only.
Envoy Gateway supports the Gateway-API defined BackendTLSPolicy.
Prerequisites
OpenSSL to generate TLS assets.
Installation
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
ClusterTrustBundle is GA and served as certificates.k8s.io/v1 by default since Kubernetes 1.37.
Save and apply the following resource to your cluster:
apiVersion:certificates.k8s.io/v1kind:ClusterTrustBundlemetadata:name:example-caspec:trustBundle:| [content from ca.crt]
Before Kubernetes 1.37, ClusterTrustBundle is only available as certificates.k8s.io/v1beta1, which is disabled by default.
Enable it on the API server with --runtime-config=certificates.k8s.io/v1beta1/clustertrustbundles=true and --feature-gates=ClusterTrustBundle=true,
then save and apply the following resource to your cluster:
apiVersion:certificates.k8s.io/v1beta1kind:ClusterTrustBundlemetadata:name:example-caspec:trustBundle:| [content from ca.crt]
Setup TLS on the backend
Patch the existing quickstart backend to enable TLS. The patch will mount the TLS certificate secret into the backend as volume.
Create a BackendTLSPolicy instructing Envoy Gateway to establish a TLS connection with the backend and validate the backend certificate is issued by a trusted CA and contains an appropriate DNS SAN.
Note: SectionName is an optional field that specifies the name of the port in the target backend. This example uses a Kubernetes Service as the backend target, so the sectionName is set to https to match the port name in the Service.
If the target is a Backend resource, the sectionName field should be set to the port number of the backend.
In addition to enablement of backend TLS with the Gateway-API BackendTLSPolicy, Envoy Gateway supports customizing TLS parameters.
To achieve this, the EnvoyProxy resource can be used to specify TLS parameters. We will customize the TLS version in this example.
First, you need to add ParametersRef in GatewayClass, and refer to EnvoyProxy Config:
Inspect the output and see that the response contains the details of the TLS handshake between Envoy and the backend.
The TLS version is now TLS1.3, as configured in the EnvoyProxy resource. The TLS cipher is also changed, since TLS1.3 supports different ciphers from TLS1.2.
This task demonstrates how to skip TLS verification for a backend service in Envoy Gateway.
By default, you must configure a BackendTLSPolicy to validate the TLS certificate of a backend service when it uses TLS.
However, in certain scenarios—such as development or testing—you might want to skip TLS verification for a backend service.
To do this, you can use the Backend API and set the tls.insecureSkipVerify field to true in the Backend resource.
Warning: Skipping TLS verification disables certificate validation, which can expose your connection to man-in-the-middle
attacks. This setting is typically used only for development or testing and is not recommended in production environments.
Prerequisites
OpenSSL to generate TLS assets.
Installation
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Enable Backend
The Backend API is disabled by default in Envoy Gateway. To enable it, follow the steps outlined in Backend Routing to configure the EnvoyGateway startup settings accordingly.
TLS Certificates
Generate the certificates and keys used by the backend to terminate TLS connections from the Gateways.
Create a root certificate and private key to sign certificates:
In the following example, we will create a Backend resource that routes to the tls-backend service, and an HTTPRoute
that references the Backend resource.
Because the backend service is using TLS, and no BackendTLSPolicy is configured to validate the TLS certificate,
the request will fail with a 400 Bad Request error:
* Connected to www.example.com (172.18.0.200) port 80* using HTTP/1.x
> GET /get HTTP/1.1
> Host:www.example.com
> User-Agent: curl/8.14.1
> Accept: */*
>
* Request completely sent off
< HTTP/1.1 400 Bad Request
< date: Thu, 31 Jul 2025 06:09:51 GMT
< transfer-encoding: chunked
Disabling TLS verification by setting the InsecureSkipVerify field to true allows the request to succeed:
You should now see a successful response from the backend service. Since TLS verification has been skipped, the request
proceeds without validating the backend’s TLS certificate. The response will include TLS details such as the protocol
version and cipher suite used for the connection.
This task provides instructions for configuring HTTP Basic authentication.
HTTP Basic authentication checks if an incoming request has a valid username and password before routing the request to
a backend service.
Envoy Gateway introduces a new CRD called SecurityPolicy that allows the user to configure HTTP Basic
authentication.
This instantiated resource can be linked to a Gateway, HTTPRoute or GRPCRoute resource.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Configuration
Envoy Gateway uses .htpasswd format to store the username-password pairs for authentication.
The file must be stored in a kubernetes secret and referenced in the SecurityPolicy configuration.
The secret is an Opaque secret, and the username-password pairs must be stored in the key “.htpasswd”.
Create a root certificate
Create a root certificate and private key to sign certificates:
First, create a .htpasswd file with the username and password you want to use for authentication.
Note: Please always use HTTPS with Basic Authentication. This prevents credentials from being transmitted in plain text.
The input password won’t be saved, instead, a hash will be generated and saved in the output file. When a request
tries to access protected resources, the password in the “Authorization” HTTP header will be hashed and compared with the
saved hash.
Note: only SHA hash algorithm is supported for now.
htpasswd -cbs .htpasswd foo bar
You can also add more users to the file:
htpasswd -bs .htpasswd foo1 bar1
Create a basic-auth secret
Next, create a kubernetes secret with the generated .htpasswd file in the previous step.
Checkout the Developer Guide to get involved in the project.
2.3.8 - CORS
This task provides instructions for configuring Cross-Origin Resource Sharing (CORS) on Envoy Gateway.
CORS defines a way for client web applications that are loaded in one domain to interact with resources in a different
domain.
Envoy Gateway introduces a new CRD called SecurityPolicy that allows the user to configure CORS.
This instantiated resource can be linked to a Gateway, HTTPRoute or GRPCRoute resource.
You can also configure CORS using the Gateway API’s HTTPCORSFilter, which offers a simpler option but
is only supported on the HTTPRoute resource.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Configuration
When configuring CORS either an origin with a precise hostname can be configured or an hostname containing a wildcard prefix,
allowing all subdomains of the specified hostname.
In addition to that the entire origin (with or without specifying a scheme) can be a wildcard to allow all origins.
A SecurityPolicy can also allow origins that match a regular expression in allowOriginRegexes.
Regular expressions use RE2 syntax, except for the \C escape sequence, which is not supported.
The regular expression must match the entire origin, including the scheme and the port if present.
A regular expression that matches the literal string * is rejected. Use allowOrigins: ["*"] to allow all origins.
Configuring CORS with SecurityPolicy
The below example defines a SecurityPolicy that allows CORS for requests originating from http://*.foo.com, and from
origins matching the regular expression https://preview-[0-9]+\.example\.com, such as https://preview-123.example.com.
It also enables credentialed requests with allowCredentials: true.
Alternatively, you can configure CORS using the Gateway API’s HTTPCORSFilter. This filter can be directly configured
within an HTTPRoute resource, which is simpler if you only need to apply CORS to a specific route.
The below example applies CORS to the backend HTTPRoute, allowing requests from http://*.foo.com.
It also enables credentialed requests with allowCredentials: true.
You won’t see any CORS headers in the response, indicating that the request from http://www.bar.com was not allowed.
If you try to send a request from http://www.foo.com:8080, you should also see similar response because the port number
8080 is not included in the allowed origins.
If you applied the SecurityPolicy, a request from https://preview-123.example.com is also allowed because it matches
the regular expression in allowOriginRegexes:
A request from https://preview-123.example.com:8443 is not allowed because the regular expression must match the
entire origin, including the port number.
Note:
CORS specification requires that the browsers to send a preflight request to the server to ask if it’s allowed
to access the limited resource in another domains. The browsers are supposed to follow the response from the server to
determine whether to send the actual request or not. The CORS filter only response to the preflight requests according to
its configuration. It won’t deny any requests. The browsers are responsible for enforcing the CORS policy.
The targeted HTTPRoute or the HTTPRoutes that the targeted Gateway routes to must allow the OPTIONS method for the CORS
filter to work. Otherwise, the OPTIONS request won’t match the routes and the CORS filter won’t be invoked.
Clean-Up
Follow the steps from the Quickstart to uninstall Envoy Gateway and the example manifest.
Delete the SecurityPolicy:
kubectl delete securitypolicy/cors-example
Next Steps
Checkout the Developer Guide to get involved in the project.
2.3.9 - Credential Injection
This task shows how to use HTTPRouteFilter to inject credentials into requests. It can be used to add
credentials such as Basic Authentication, JWTs, or API keys before the requests are sent to the backend service.
This is useful in scenarios where the backend service requires authentication or other credentials that are not provided
by the client. For example, you can use this feature to inject an access token into an API call to AWS.
Credentials can be injected at the HTTPRoute level or at the BackendRef level, allowing for fine-grained control over
which requests receive injected credentials.
The same HTTPRouteFilter can also be referenced from a GRPCRoute via an extensionRef filter, so
credentials can be injected into gRPC traffic in the same way. Note that, for a GRPCRoute, the filter is only supported
at the rule level; referencing it at the BackendRef level is not supported.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Configuration
To inject credentials into requests, you need to create a HTTPRouteFilter resource that defines the
credentials to be injected. The filter can be applied to an HTTPRoute or a BackendRef resource.
Create a Secret with the Credential that you want to inject into requests
Create a secret with the credential you want to inject into requests. The secret should contain the credential in a field
named credential.
You can use any type of credential, such as a JWT token, Basic Authentication credentials, an API key,
or a custom credential. In this example, we will use a JWT token as the credential to be injected into requests.
Create a HTTPRouteFilter resource that injects the JWT token into requests.
By default, the credentials will be injected into the Authorization header. You can also inject credentials into other
headers by specifying the header field in the credentialInjection section of the HTTPRouteFilter.
If the Authorization header or the specified header already exists in the request, the credentials won’t be injected
unless you set overwrite to true.
To inject the credentials at the HTTPRoute level, you need to reference the HTTPRouteFilter in the filters
section of the HTTPRoute resource. The credentials will be injected into all requests that match the route.
To inject the credentials at the BackendRef level, you need to reference the HTTPRouteFilter in the
filters section of the BackendRef resource. The credentials will be injected into all requests that are sent to that
backend.
You should see the Authorization header with the JWT token in the echoed request headers in the response, indicating
that the token was successfully injected into the request.
Check out the Developer Guide to get involved in the project.
2.3.10 - CSRF
This task provides instructions for configuring Cross-Site Request Forgery (CSRF) protection on Envoy Gateway.
CSRF is an attack that tricks a user’s browser into making unintended requests to a different site where the user is
authenticated.
Envoy Gateway introduces a new field in the SecurityPolicy CRD that allows the user to configure CSRF protection.
This instantiated resource can be linked to a Gateway, HTTPRoute or GRPCRoute resource.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Configuration
When CSRF protection is enabled, the Envoy CSRF filter validates that the Origin header of mutating requests
(POST, PUT, DELETE, PATCH) matches the destination or one of the configured additional origins.
Non-mutating requests (GET, HEAD, OPTIONS) are not affected.
additionalOrigins uses the same origin syntax as cors.allowOrigins: a full origin such as
https://www.example.com, a single wildcard label such as https://*.trusted.com, an explicit port such as
http://www.example.com:8080, or * to allow any origin.
Note: Envoy’s CSRF filter compares against the host and port of the origin only, so the scheme is ignored.
https://www.example.com and http://www.example.com are equivalent, and either one allows the request
whichever scheme the client used. The scheme is still required by the syntax so that origins read the same
way here as they do in cors.allowOrigins.
The filter supports gradual rollout via shadowFraction: the fraction of requests that are evaluated in
dry-run mode instead of being enforced. It is expressed as a numerator and an optional denominator that
defaults to 100, and defaults to 0%, i.e. all requests are enforced.
The below example defines a SecurityPolicy that enables CSRF protection and allows www.example.com and any
subdomain of trusted.com as additional origins.
In this mode, all requests are allowed but Envoy tracks CSRF metrics (request_valid / request_invalid)
so you can monitor the impact before enabling enforcement.
Requests that are not selected for shadowing are enforced, so shadowFraction also doubles as the knob for
rolling enforcement out gradually: numerator: 25 shadows a quarter of the requests and enforces the
remaining three quarters. Lower it towards 0 as the metrics confirm that no legitimate origin is rejected.
2.3.11 - External Authorization
This task provides instructions for configuring external authorization.
External authorization calls an external HTTP or gRPC service to check whether an incoming HTTP request is authorized
or not. If the request is deemed unauthorized, then the request will be denied with a 403 (Forbidden) response. If the
request is authorized, then the request will be allowed to proceed to the backend service.
Envoy Gateway introduces a new CRD called SecurityPolicy that allows the user to configure external authorization.
This instantiated resource can be linked to a Gateway and HTTPRoute resource.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
Create a new SecurityPolicy resource to configure the external authorization. This SecurityPolicy targets the HTTPRoute
“myApp” created in the previous step. It calls the HTTP external authorization service “http-ext-auth” on port 9002 for
authorization. The headersToBackend field specifies the headers that will be sent to the backend service if the request
is successfully authorized.
The request should be allowed and you should see the response from the backend service.
Because the x-current-user header from the auth response has been sent to the backend service,
you should see the x-current-user header in the response.
"X-Current-User": [
"user1"
],
GRPC External Authorization Service
Installation
Install a demo gRPC service that will be used as the external authorization service. The demo gRPC service is enabled
with TLS and a BackendTLSConfig is created to configure the communication between the Envoy proxy and the gRPC service.
Note: TLS is optional for HTTP or gRPC external authorization services. However, enabling TLS is recommended for enhanced
security in production environments.
The HTTPRoute created in the previous section is still valid and can be used with the gRPC auth service, but if you have
not created the HTTPRoute, you can create it now.
Create a new HTTPRoute resource to route traffic on the path /myapp to the backend service.
Update the SecurityPolicy that was created in the previous section to use the gRPC external authorization service.
It calls the gRPC external authorization service “grpc-ext-auth” on port 9002 for authorization.
kubectl get securitypolicy/ext-auth-example -o yaml
Because the gRPC external authorization service is enabled with TLS, a BackendTLSConfig needs to be created to configure
the communication between the Envoy proxy and the gRPC auth service.
Use bodyToExtAuth to buffer the request body and send it to the external authorization service.
maxRequestBytes sets the largest body that will be buffered; requests with a larger body are rejected with HTTP 413.
It defaults to 32768 bytes (32KiB).
By default, the body is sent to a gRPC external authorization service as a UTF-8 string in the body field.
Set packAsBytes: true to send it as raw bytes in the raw_body field instead. Use this for binary or
non-UTF-8 bodies, such as protobuf payloads, file uploads, or compressed content.
packAsBytes only works with gRPC external authorization services. An HTTP external authorization
service always receives the raw request body, so enabling packAsBytes with http is rejected.
Checkout the Developer Guide to get involved in the project.
2.3.12 - GeoIP Authorization
This task provides instructions for configuring GeoIP-based authorization with Envoy Gateway.
GeoIP authorization uses geolocation data derived from the client IP address to determine whether a request should be
allowed or denied before it is forwarded to the backend service.
Envoy Gateway introduces a new CRD called SecurityPolicy that allows the user to configure GeoIP-based authorization.
This instantiated resource can be linked to a Gateway, HTTPRoute, or GRPCRoute resource.
GeoIP authorization is configured through SecurityPolicy.spec.authorization.rules[].principal.clientIPGeoLocations.
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
To keep this guide readable, the full base64-encoded ConfigMap is not repeated here.
For production deployments, mount your own supported MaxMind database and update the file path in the EnvoyProxy resource accordingly.
Configure the Gateway and EnvoyProxy
The following resources create a dedicated Gateway, mount the anonymous-IP database into the Envoy proxy, and configure EnvoyProxy.spec.geoIP.provider.maxMind.anonymousIpDbSource to read it.
The following resources create an HTTPRoute for /geo-anonymous and attach a SecurityPolicy that denies requests identified as anonymous networks while allowing other traffic.
kubectl get securitypolicy/authorization-geoip-anonymous -o yaml
Enable client IP detection
The geoip filter resolves the client IP from one of three sources, configured via ClientTrafficPolicy.spec.clientIPDetection:
xForwardedFor — read the client IP from the X-Forwarded-For header, trusting numTrustedHops rightmost entries.
customHeader — read the client IP from a trusted custom HTTP header populated by an upstream load balancer.
directSourceIP — use the downstream TCP connection source address. Use this in L4-transparent topologies where a load balancer preserves the original client source IP at TCP level (e.g. AWS NLB with target-type: instance + externalTrafficPolicy: Local, Azure Standard Load Balancer).
The following ClientTrafficPolicy tells Envoy Gateway to use the X-Forwarded-For header and trust one upstream hop:
In this example, requests are allowed only if the x-user-id request header matches one of the configured allowed values.
Method-Based Authorization
Method-based authorization restricts access based on the HTTP method of incoming requests.
This can be used to allow or deny specific operations such as GET, POST, or DELETE.
Example
apiVersion:gateway.envoyproxy.io/v1alpha1kind:SecurityPolicymetadata:name:method-authspec:targetRefs:- group:gateway.networking.k8s.iokind:Gatewayname:gateway-1authorization:defaultAction:Denyrules:- name:allow-read-methodsaction:Allowoperation:methods:- GET- POST
In this configuration, only GET and POST requests are permitted. Any other HTTP methods (such as PUT or DELETE) will be denied by default.
Combined Header and Method Authorization
Header-based and method-based authorization can be combined within a single authorization rule for more granular access control.
In this scenario, a request is authorized only if it uses an allowed HTTP method and matches the configured header-based principal conditions.
Behavior Notes
Authorization semantics: Rules define authorization behavior, not request authentication.
Logical AND: Conditions within a rule use logical AND semantics. Requests must satisfy all configured header and method requirements.
Rule Evaluation: Rules are evaluated in the order they are defined.
Default Action: Requests that do not match any rule are handled according to the configured defaultAction.
2.3.14 - IP Allowlist/Denylist
This task provides instructions for configuring IP allowlist/denylist on Envoy Gateway. IP allowlist/denylist
checks if an incoming request is from an allowed IP address before routing the request to a backend service.
Envoy Gateway introduces a new CRD called SecurityPolicy that allows the user to configure IP allowlist/denylist.
This instantiated resource can be linked to a Gateway, HTTPRoute, GRPCRoute, TCPRoute or UDPRoute resource.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Configuration
Create a SecurityPolicy
The below SecurityPolicy restricts access to the backend service by allowing requests only from the IP addresses 10.0.1.0/24.
In this example, the default action is set to Deny, which means that only requests from the specified IP addresses with Allow
action are allowed, and all other requests are denied. You can also change the default action to Allow to allow all requests
except those from the specified IP addresses with Deny action.
Note
This example targets an HTTPRoute, but IP allowlists and denylists work the same way at L4: point targetRefs at a
TCPRoute or a UDPRoute instead, or at a Gateway listener serving either protocol.
On an L4 route only clientCIDRs authorization applies, because there is no HTTP request to inspect. JWT, header and
geolocation principals, CEL expressions and operation matches are HTTP-only and a policy using them on a TCPRoute
or UDPRoute is rejected. A denied connection is closed and a denied datagram is dropped without a reply, rather than
receiving an error response.
kubectl get securitypolicy/authorization-client-ip -o yaml
Original Source IP
It’s important to note that the IP address used for allowlist/denylist is the original source IP address of the request.
You can use a ClientTrafficPolicy to configure how Envoy Gateway should determine the original source IP address.
This section applies to HTTPRoute and GRPCRoute. A TCPRoute or UDPRoute carries no HTTP headers, so the client
IP is always taken from the connection peer or the source address of the datagram, and the X-Forwarded-For settings
below have no effect on it. If a load balancer or NAT sits in front of the gateway, the original client IP survives
only when that intermediary preserves the source address — for example by enabling the PROXY protocol, which is not
available on the UDP path.
For example, the below ClientTrafficPolicy configures Envoy Gateway to use the X-Forwarded-For header to determine the original source IP address.
The numTrustedHops field specifies the number of trusted hops in the X-Forwarded-For header. In this example, the numTrustedHops is set to 1,
which means that the first rightmost IP address in the X-Forwarded-For header is used as the original source IP address.
Checkout the Developer Guide to get involved in the project.
2.3.15 - JWT Authentication
This task provides instructions for configuring JSON Web Token (JWT) authentication. JWT authentication checks
if an incoming request has a valid JWT before routing the request to a backend service. Currently, Envoy Gateway only
supports validating a JWT from an HTTP header, e.g. Authorization: Bearer <token>.
Envoy Gateway introduces a new CRD called SecurityPolicy that allows the user to configure JWT authentication.
This instantiated resource can be linked to a Gateway, HTTPRoute or GRPCRoute resource.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
Two HTTPRoute has been created, one for /foo and another for /bar. A SecurityPolicy has been created and targeted
HTTPRoute foo to authenticate requests for /foo. The HTTPRoute bar is not targeted by the SecurityPolicy and will allow
unauthenticated requests to /bar.
Verify the HTTPRoute configuration and status:
kubectl get httproute/foo -o yaml
kubectl get httproute/bar -o yaml
The SecurityPolicy is configured for JWT authentication and uses a single JSON Web Key Set (JWKS)
provider for authenticating the JWT.
Connect to a remote JWKS with Self-Signed Certificate
To connect to a remote JWKS with a self-signed certificate, you need to configure it using the BackendTLSPolicy to specify the CA certificate required to authenticate the JWKS host. Additionally, if the JWKS is outside of the cluster, you need to configure the Backend resource to specify the JWKS host.
The following example demonstrates how to configure the remote JWKS with a self-signed certificate.
Please note that the Backend resource is not required if the JWKS is hosted on the same cluster as the Envoy Gateway, since
it can be accessed directly via the Kubernetes Service DNS name.
As shown in the example above, the SecurityPolicy resource is configured with a remote JWKS within its JWT settings. The backendRefs field references the Backend resource that defines the JWKS host. The BackendTLSPolicy resource specifies the CA certificate required to authenticate the JWKS host.
Additional connection settings for the remote JWKS host can be configured in the backendSettings. Currently, only the retry policy is supported.
With the above configuration, the SecurityPolicy resource will use the JWKS stored in the jwt-local-jwks ConfigMap to authenticate requests for the foo HTTPRoute.
Clean-Up
Follow the steps from the Quickstart to uninstall Envoy Gateway and the example manifest.
Delete the SecurityPolicy:
kubectl delete securitypolicy/jwt-example
Next Steps
Checkout the Developer Guide to get involved in the project.
2.3.16 - JWT Claim-Based Authorization
This task provides instructions for configuring JWT claim-based authorization. JWT claim-based authorization checks if an incoming request has the required JWT claims before routing the request to a backend service.
Envoy Gateway introduces a new CRD called SecurityPolicy that allows the user to configure JWT claim-based authorization.
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Configuration
Create a SecurityPolicy
Please note that the JWT claim-based authorization requires the JWT token to be present in the request. A JWT authentication must be configured in the same SecurityPolicy to validate the JWT token and extract the claims.
The below SecurityPolicy configuration allows requests with a valid JWT token that has the following claims:
Checkout the Developer Guide to get involved in the project.
2.3.17 - Mutual TLS: External Clients to the Gateway
This task demonstrates how mutual TLS can be achieved between external clients and the Gateway.
This task uses a self-signed CA, so it should be used for testing and demonstration purposes only.
Prerequisites
OpenSSL to generate TLS assets.
Installation
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
Checkout the Developer Guide to get involved in the project.
2.3.18 - OIDC Authentication
This task provides instructions for configuring OpenID Connect (OIDC) authentication.
OpenID Connect (OIDC) is an authentication standard built on top of OAuth 2.0.
It enables EG to rely on authentication that is performed by an OpenID Connect Provider (OP)
to verify the identity of a user.
Envoy Gateway introduces a new CRD called SecurityPolicy that allows the user to configure OIDC
authentication.
This instantiated resource can be linked to a Gateway and HTTPRoute resource.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
EG OIDC authentication requires the redirect URL to be HTTPS. Follow the Secure Gateways guide
to generate the TLS certificates and update the Gateway configuration to add an HTTPS listener.
Verify the Gateway status:
kubectl get gateway/eg -o yaml
Let’s create an HTTPRoute that represents an application protected by OIDC.
OIDC can be configured at the Gateway level to authenticate all the HTTPRoutes that are associated with the Gateway with
the same OIDC configuration, or at the HTTPRoute level to authenticate each HTTPRoute with different OIDC configurations.
This section demonstrates how to configure OIDC authentication for a specific HTTPRoute.
Register an OIDC application
This task uses Google as the OIDC provider to demonstrate the configuration of OIDC. However, EG works with any OIDC
providers, including Auth0, Azure AD, Keycloak, Okta, OneLogin, Salesforce, UAA, etc.
Follow the steps in the Google OIDC documentation to register an OIDC application. Please make sure the
redirect URL is set to the one you configured in the SecurityPolicy that you will create in the step below. In this example,
the redirect URL is https://www.example.com:8443/myapp/oauth2/callback.
After registering the application, you should have the following information:
Client ID: The client ID of the OIDC application.
Client Secret: The client secret of the OIDC application.
Create a kubernetes secret
Next, create a kubernetes secret with the Client Secret created in the previous step. The secret is an Opaque secret,
and the Client Secret must be stored in the key “client-secret”.
Note: please replace the ${CLIENT_SECRET} with the actual Client Secret that you got from the previous step.
Please notice that the redirectURL and logoutPath must match the target HTTPRoute. In this example, the target
HTTPRoute is configured to match the host www.example.com and the path /myapp, so the redirectURL must be prefixed
with https://www.example.com:8443/myapp, and logoutPath must be prefixed with/myapp, otherwise the OIDC authentication
will fail because the redirect and logout requests will not match the target HTTPRoute and therefore can’t be processed
by the OAuth2 filter on that HTTPRoute.
Note: please replace the ${CLIENT_ID} in the below yaml snippet with the actual Client ID that you got from the OIDC provider.
Put www.example.com in the /etc/hosts file in your test machine, so we can use this host name to access the gateway from a browser:
...
127.0.0.1 www.example.com
Open a browser and navigate to the https://www.example.com:8443/myapp address. You should be redirected to the Google
login page. After you successfully login, you should see the response from the backend service.
Clean the cookies in the browser and try to access https://www.example.com:8443/foo address. You should be able to see
this page since the path /foo is not protected by the OIDC policy.
OIDC Authentication for a Gateway
OIDC can be configured at the Gateway level to authenticate all the HTTPRoutes that are associated with the Gateway with
the same OIDC configuration, or at the HTTPRoute level to authenticate each HTTPRoute with different OIDC configurations.
This section demonstrates how to configure OIDC authentication for a Gateway.
Register an OIDC application
If you haven’t registered an OIDC application, follow the steps in the previous section to register an OIDC application.
Create a kubernetes secret
If you haven’t created a kubernetes secret, follow the steps in the previous section to create a kubernetes secret.
Create an HTTPRoute with a different subdomain
Let’s create another HTTPRoute in the same Gateway, but with a different subdomain.
Create or update the SecurityPolicy to target the Gateway instead of the HTTPRoute. Please notice that the redirectURL
and logoutPath must match one of the HTTPRoutes associated with the Gateway. In this example, the target Gateway has
three HTTPRoutes associated with it, one with the host www.example.com and the path /myapp, one with the host
www.example.com and the path /, and one with the host foo.example.com and the path /. Any of these HTTPRoutes
can be used to match the redirectURL and logoutPath.
By default, the access token and ID token cookies are set to the host of the request, excluding subdomains. To allow the
token cookies to be shared across subdomains and prevent users from having to log in again when switching between subdomains,
the cookieDomain field needs to be set to the root domain. In this example, the root domain is example.com.
Note: if a cookieDomain is added to an existing SecurityPolicy, the cookies in the browser must be cleared before sending a new request to the Gateway, otherwise the cookies with the old subdomain will take precedence and be sent to the Gateway, causing the OIDC authentication to fail.
If you haven’t done so, follow the steps in the previous section to port forward gateway port to localhost and put
www.example.com in the /etc/hosts file in your test machine.
Also, put foo.example.com in the /etc/hosts file in your test machine.
...
127.0.0.1 foo.example.com
Open a browser and navigate to the https://www.example.com:8443/myapp address. You should be redirected to the Google
login page. After you successfully login, you should see the response from the backend service.
You can also try to access https://foo.example.com:8443 and https://www.example.com:8443/bar addresses. You should
be able to see the response from the backend service since these HTTPRoutes are also protected by the same OIDC config,
and the cookies are shared across subdomains.
Connect to an OIDC Provider with Self-Signed Certificate
In some scenarios, the OIDC provider may use a self-signed certificate. To connect to an OIDC provider with a self-signed certificate, you need to configure it using the Backend resource within the SecurityPolicy. Additionally, use the BackendTLSPolicy to specify the CA certificate required to authenticate the OIDC provider.
The following example demonstrates how to configure the OIDC provider with a self-signed certificate.
As shown in the example above, the SecurityPolicy resource is configured with an OIDC provider in its OIDC settings. The backendRefs field references the Backend resource that defines the OIDC provider. The BackendTLSPolicy resource specifies the CA certificate required to authenticate the OIDC provider.
Additional connection settings for the OIDC provider can be configured in the backendSettings. Currently, only the retry policy is supported.
Envoy keeps the OIDC session in a set of cookies, and names each one <Purpose>-<suffix>,
for example AccessToken-1a2b3c4d. Envoy Gateway derives the suffix from the identity of
the SecurityPolicy, so that policies applying to the same route don’t overwrite each
other’s cookies.
Because the generated suffix is tied to the identity of the policy, it changes when the
policy is deleted and recreated, which logs users out. Pin it with cookieNames.suffix:
oidc:cookieNames:suffix:"myapp"
Envoy then sets AccessToken-myapp, IdToken-myapp, OauthHMAC-myapp,
OauthExpires-myapp, RefreshToken-myapp, OauthNonce-myapp and
CodeVerifier-myapp.
Policies that share a suffix also share the session cookies, so a user authenticated
through one is authenticated through the others. This only works if those policies agree
on the OIDC provider, the client, and the cookieDomain.
If something that runs after OIDC expects a particular cookie name, name that cookie
outright. A filter later in the chain, or the backend application itself, may read a token
from a cookie whose name it hardcodes, most often the access token. The per-cookie fields
take precedence over suffix:
Here Envoy sets my_access_token, and keeps the suffix for the cookies that aren’t named
explicitly, such as IdToken-myapp and OauthHMAC-myapp.
Each cookie holds a different value, so all the resulting names must be distinct.
Large Tokens
Browsers don’t store a cookie larger than 4096 bytes, and they drop it without an error.
Some OIDC providers issue access, ID or refresh tokens larger than that, for example when
the token carries many group claims. A browser that drops the token cookie never sends the
token back: Envoy treats the session as missing and redirects the user to the OIDC provider
again and again, until the browser reports too many redirects.
Envoy Gateway therefore has Envoy split such a token across several cookies. A token that
fits in one cookie is still written as one cookie. A larger token is written as <name>_0,
<name>_1, and so on, plus a <name>_chunks cookie that holds the count, for example
AccessToken-myapp_0 and AccessToken-myapp_chunks. Each cookie stays within 4096 bytes,
name and attributes included, and a token is split into at most 8 cookies. If a token needs
more, Envoy fails the login with a 503 instead of setting cookies the browser could not
send back.
Every chunk is sent back on each request, so several large tokens together can exceed the
listener’s request header limit, 60Ki by default. Raise it with headers.maxRequestHeaderLimit
in a ClientTrafficPolicy if requests with a full set of chunks start failing.
Envoy Proxy older than v1.40 can’t read the split cookies. While proxies of an earlier Envoy
Gateway release serve the same hostnames, for example during an upgrade or while the clusters
of a multi-cluster setup are upgraded one by one, a client that holds such a token in one
cookie today, such as a non-browser client, is sent back to the OIDC provider whenever it
reaches an older proxy. To avoid that, disable the OIDCTokenCookieChunking runtime flag in
the EnvoyGateway configuration until every proxy is upgraded:
From v1.40 on, Envoy reads both a single cookie and split cookies whether or not the flag
is enabled, so turning the flag on or off doesn’t end existing sessions.
Logout
Requesting the logoutPath clears the OIDC cookies Envoy Gateway set for the session. If not
specified, logoutPath defaults to /logout. Like redirectURL, it must match the target
HTTPRoute or Gateway, otherwise the logout request can’t be processed by the OIDC filter.
Clearing the cookies only ends the session at the gateway; the user remains logged in at the OIDC
provider. To also terminate the provider-side session, configure the provider’s
end session endpoint, which enables
RP-Initiated Logout:
Envoy Gateway also discovers endSessionEndpoint from the provider’s
Well-Known Configuration Endpoint
when authorizationEndpoint or tokenEndpoint is not specified, so RP-Initiated Logout may be
active even if you did not set the field explicitly.
When an end session endpoint is in use, requesting the logoutPath returns a redirect to the
provider that carries a post_logout_redirect_uri parameter telling the provider where to send the
user once the logout completes. By default Envoy sends the root of the request’s host,
<scheme>://<host>/.
Setting the post logout redirect URI
Most providers require the post logout redirect URI to be registered for the client and reject
the logout request otherwise. If the default value is not registered, set an explicit URI:
Point the URI at a page that the OIDC policy does not protect. If it falls under a protected route,
Envoy Gateway starts a new login as soon as the provider redirects the user there, and the provider
may sign the user straight back in with its own session.
The URI may contain the Envoy %REQ(header)%command operator, which is useful
when the same policy serves more than one host:
Only %REQ(header)% is accepted here, since it is the only operator meaningful in a URI derived from
the request. Envoy Gateway rejects any other operator and reports the error on the SecurityPolicy
status, so that a typo such as %REQ(x-tenant) or %BOGUS% surfaces on the policy rather than
causing Envoy to reject the configuration. Envoy percent-encodes the URI when it builds the logout
redirect, so write it unencoded; a literal percent is written as %%.
Omitting the post logout redirect URI
post_logout_redirect_uri is optional in the OIDC specification. If you cannot register a URI with
your provider, or you do not need the user redirected back to your application, omit the parameter
entirely:
The logout itself still completes — Envoy Gateway clears its cookies and the provider terminates the
session — but because the provider is not told where to send the user, the browser is left on a page
controlled by the provider rather than returning to your application.
uri cannot be set together with disabled: true. postLogoutRedirect has no effect when no end
session endpoint is configured or discovered, because in that case Envoy Gateway does not redirect to
the provider at all.
Providers
Guides to integrate with specific OIDC providers.
Azure Entra
This guide demonstrates how to configure Envoy Gateway to use Azure Entra as the OIDC provider with additional JWT authorization. To get OAuth 2.0 compatible tokens you must register a Scope for your application as described in the Microsoft Documentation. In this example the resulting scope is api://custom/EnvoyGateway.OIDC.
Checkout the Developer Guide to get involved in the project.
2.3.19 - Secure Gateways
This task will help you get started using secure Gateways.
This task uses a self-signed CA, so it should be used for testing and demonstration purposes only.
Prerequisites
OpenSSL to generate TLS assets.
Installation
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
TLS Certificates
Generate the certificates and keys used by the Gateway to terminate client TLS connections.
For certificates delivered by an external SDS server, see SDS Certificate References.
Create a root certificate and private key to sign certificates:
Online Certificate Status Protocol (OCSP) stapling allows the gateway to proactively attach proof that a certificate is still valid, eliminating the need for each client to query the certificate authority (CA) during the TLS handshake. This reduces latency and prevents client browsing information from being exposed to the CA.
Envoy Gateway supports OCSP stapling by attaching an OCSP response during the TLS handshake whenever the Gateway listener’s certificate Secret includes one. Specifically, Envoy Gateway looks for the OCSP response in the Secret’s tls.ocsp-staple data field. If present, Envoy Gateway staples the response to the handshake automatically.
Testing
Get the External IP of the Gateway:
exportGATEWAY_HOST=$(kubectl get gateway/eg -o jsonpath='{.status.addresses[0].value}')
Follow the steps in the Testing section to test connectivity to the backend app through both Gateway
listeners. Replace www.example.com with foo.example.com to test the new HTTPS listener.
Cross Namespace Certificate References
A Gateway can be configured to reference a certificate in a different namespace. This is allowed by a ReferenceGrant
created in the target namespace. Without the ReferenceGrant, a cross-namespace reference is invalid.
Before proceeding, ensure you can query the HTTPS backend service from the Testing section.
To demonstrate cross namespace certificate references, create a ReferenceGrant that allows Gateways from the “default”
namespace to reference Secrets in the “envoy-gateway-system” namespace:
The Gateway HTTPS listener should now surface the Ready: False status condition and the example HTTPS backend should
no longer be reachable through the Gateway.
kubectl get gateway/eg -o yaml
Recreate the example Secret in the envoy-gateway-system namespace:
The Gateway HTTPS listener status should now surface the Ready: True condition and you should once again be able to
query the HTTPS backend through the Gateway.
This section gives a walkthrough to generate RSA and ECDSA derived certificates and keys for the Server, which can then be configured in the Gateway listener, to terminate TLS traffic.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Follow the steps in the TLS Certificates section to generate self-signed RSA derived Server certificate and private key, and configure those in the Gateway listener configuration to terminate HTTPS traffic.
Pre-checks
Get the External IP of the Gateway:
exportGATEWAY_HOST=$(kubectl get gateway/eg -o jsonpath='{.status.addresses[0].value}')
Query the example app through Envoy Proxy while enforcing an RSA cipher:
The command above fails with the following message:
* Added www.example.com:8443:127.0.0.1 to DNS cache
* Hostname www.example.com was found in DNS cache
* Trying 127.0.0.1:8443...
* Connected to www.example.com (127.0.0.1) port 8443 (#0)
* ALPN: offers h2
* ALPN: offers http/1.1
* Cipher selection: ECDHE-ECDSA-CHACHA20-POLY1305
* CAfile: example.com.crt
* CApath: none
* (304) (OUT), TLS handshake, Client hello (1):
* error:1404B410:SSL routines:ST_CONNECT:sslv3 alert handshake failure
* Closing connection 0
Moving forward in the doc, we will be configuring the existing Gateway listener to accept both kinds of ciphers.
TLS Certificates
Reuse the CA certificate and key pair generated in the Secure Gateways task and use this CA to sign both RSA and ECDSA Server certificates.
Note the CA certificate and key names are example.com.crt and example.com.key respectively.
Create an ECDSA certificate and a private key for www.example.com:
This sections gives a walkthrough to generate multiple certificates corresponding to different FQDNs. The same Gateway listener can then be configured to terminate TLS traffic for multiple FQDNs based on the SNI matching.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Follow the steps in the TLS Certificates section to generate self-signed RSA derived Server certificate and private key, and configure those in the Gateway listener configuration to terminate HTTPS traffic.
Additional Configurations
Using the TLS Certificates section, we first generate additional Secret for another Host www.sample.com.
Since the multiple certificates are configured on the same Gateway listener, Envoy was able to provide the client with appropriate certificate based on the SNI in the client request.
Customize Gateway TLS Parameters
In addition to enablement of TLS with Gateway-API, Envoy Gateway supports customizing TLS parameters.
To achieve this, the ClientTrafficPolicy resource can be used to specify TLS parameters.
We will customize the minimum supported TLS version in this example to TLSv1.3.
The output shows that the connection fails due to an unsupported TLS protocol version used by the client. Now, connect to the Gateway without specifying a client version, and note that the connection is established with TLSv1.3.
The output shows that the connection fails due to an unsupported TLS protocol version used by the client. Now, connect
to the Gateway without specifying a client version, and note that the connection is established with TLSv1.3.
Checkout the Developer Guide to get involved in the project.
2.3.20 - Threat Model
Envoy Gateway Threat Model and End User Recommendations
About
This work was performed by ControlPlane and commissioned by the Linux Foundation. ControlPlane is a global cloud native and open source cybersecurity consultancy, trusted as the partner of choice in securing: multinational banks; major public clouds; international financial institutions; critical national infrastructure programs; multinational oil and gas companies, healthcare and insurance providers; and global media firms.
Threat Modelling Team
James Callaghan, Torin van den Bulk, Eduardo Olarte
Reviewers
Arko Dasgupta, Matt Turner, Zack Butcher, Marco De Benedictis
Introduction
As we embrace the proliferation of microservice-based architectures in the cloud-native landscape, simplicity in setup and configuration becomes paramount as DevOps teams face the challenge of choosing between numerous similar technologies. One such choice which every team deploying to Kubernetes faces is what to use as an ingress controller. With a plethora of options available, and the existence of vendor-specific annotations leading to small inconsistencies between implementations, the Gateway API project was introduced by the SIG-NETWORK community, with the goal of eventually replacing the Ingress resource.
Envoy Gateway is configured by Gateway API resources, and serves as an intuitive and feature-rich wrapper over the widely acclaimed Envoy Proxy. With a convenient setup based on Kubernetes (K8s) manifests, Envoy Gateway streamlines the management of Envoy Proxy instances in an edge-proxy setting, reducing the operational overhead of managing low-level Envoy configurations. Envoy Gateway benefits cloud-native DevOps teams through its role-oriented configuration, providing granular control based on Role-Based Access Control (RBAC) principles. These features form the basis of our exploration into Envoy Gateway and the rich feature set it brings to the table.
In this threat model, we aim to provide an analysis of Envoy Gateway’s design components and their capabilities (at version 1.0) through a threat-driven approach. It should be noted that this does not constitute a security audit of the Envoy Gateway project, but instead focuses on different possible deployment topologies for Envoy Gateway with the goal of deriving recommendations and best practice guidance for end users.
The Envoy Gateway project recommends a multi-tenancy model whereby each tenant deploys their own Envoy Gateway controller in a namespace which they own. We will also explore the implications and risks associated with multiple tenants using a shared controller.
Scope
The primary focus of this threat model is to identify and assess security risks associated with deploying and operating Envoy Gateway within a multi-tenant Kubernetes (K8s) cluster. This model aims to provide a comprehensive understanding of the system, its transmission points, and potential vulnerabilities to enumerated threats.
In Scope
Envoy Gateway: As the primary focus of this threat model, all aspects of Envoy Gateway, including its configuration, deployment, and operation will be analysed. This includes how the gateway manages TLS certificates, authentication, service-to-service traffic routing, and more.
Kubernetes Cluster: Configuration and operation of the underlying Kubernetes cluster, including how it manages network policies, access control, and resource isolation for different namespaces/tenants in relation to Envoy will be considered.
Tenant Workloads: Tenant workloads (and the pods they run on) will be considered, focusing on how they interact with the Envoy Gateway and potential vulnerabilities that could be exploited.
Out of Scope
This threat model will not consider security risks associated with the underlying infrastructure (e.g., EC2 compute instances and S3 buckets) or non-Envoy related components within the Kubernetes Cluster. It will focus solely on the Envoy Gateway and its interaction with the Kubernetes cluster and tenant workloads.
Implementation of Envoy Gateway as an egress traffic controller is out of scope for this threat model and will not be considered in the report’s findings.
To provide an in-depth look into both the system design and end-user deployment of Envoy Gateway, we will be focusing on the Deployment Architecture Diagram below.
The Deployment Architecture Diagram provides a high-level model of an end-user deployment of Envoy Gateway. For simplicity, we will look at different deployment topologies on a single multi-tenant Kubernetes cluster. Envoy Gateway operates as an edge proxy within this environment, handling the traffic flow between external interfaces and services within the cluster. The example will use two Envoy Gateway controllers - one dedicated controller for a single tenant, and one shared controller for two other tenants. Each Envoy Gateway controller will accept a single GatewayClass resource.
Deployment Architecture Diagram
As Envoy Gateway implements the Kubernetes GatewayAPI, this threat model will focus on the key objects in the Gateway API resource model:
GatewayClass: defines a set of gateways with a commonconfiguration and behaviour. It is a cluster scoped resource.
Gateway: requests a point where traffic can be translated to Services within the cluster.
Routes: describe how traffic coming via the Gateway maps to theServices.
At the time of writing, Envoy Gateway only supports a Kubernetes provider. As such, we will consider a reference architecture where multiple teams are working on the same Kubernetes cluster within different namespaces (Tenant A, B, & C). We will assume that some teams have similar security and performance needs, and a decision has been made to use a shared Gateway. However, we will also consider the case that some teams require dedicated Gateways, perhaps for compliance reasons or requirements driven by an internal threat model.
Infrastructure provider: The infrastructure provider (infra) is responsible for the overall environment that the cluster(s) are operating in. Examples include: the cloud provider (AWS, Azure, GCP, …) or the PaaS provider in a company.
Cluster operator: The cluster operator (ops) is responsible for administration of entire clusters. They manage policies, network access, application permissions.
Application developer: The application developer (dev) is responsible for defining their application configuration (e.g. timeouts, request matching/filter) and Service composition (e.g. path routing to backends).
Application admin: The application admin has administrative access to some namespaces within a cluster, but not the cluster as a whole.
Our threat model will be based on the high-level setup shown below, where Envoy is used in an edge-proxy scenario:
The following use cases will be considered, in line with the Envoy Gateway tasks:
Routing and controlling traffic, including:
a. HTTP b. TCP c. UDP d. gRPC e.TLS passthrough
TLS termination
Request Authentication
Rate Limiting
Key Assumptions
This section outlines the foundational premises that shape our analysis and recommendations for the deployment and management of Envoy Gateway within an organisation. The key assumptions are as follows:
1. Kubernetes Provider: For the purposes of this analysis, we assume that a K8s provider will be used to host the cluster.
2. Multi-tenant cluster: In order to produce a broad set of recommendations, it is assumed that within the single cluster, there is:
A dedicated cluster operation (ops) team responsible for maintaining the core cluster infrastructure.
Multiple application teams who wish to define their own Gateway resources, which will route traffic to their respective applications.
3. Soft multi-tenancy model: It is assumed that co-tenants will have some level of trust between themselves, and will not act in an overtly hostile manner to each other.
4. Ingress Control: It’s assumed that Envoy Gateway is the only ingress controller in the K8s cluster as multiple controllers can lead to complex routing challenges and introduce out-of-scope security vulnerabilities.
5. Container Security: This threat model focuses on evaluating the security of the Envoy Gateway and Envoy Proxy images. All other container images running in tenant clusters, not associated with the edge proxy deployment, are assumed to be secure and obtained from trusted registries such as Docker Hub or Google Container Registry (GCR).
6. Cloud Provider Security: It is assumed that the K8s cluster is running on secure cloud infrastructure provided by a trusted Cloud Service Provider (CSP) such as AWS, GCP, or Azure Cloud.
Data
Data Dictionary
Ultimately, the data of interest in a threat model is the business data processed by the system in question. However, in the case of this threat model, we are looking at a generic deployment architecture involving Envoy Gateway in order to draw out a set of generalised threats which can be considered by teams looking to adopt an implementation of Gateway API. As such, we do not know the business impacts of a compromise of confidentiality, integrity or availability that would typically be captured in a data impact assessment. Instead, will we base our threat assessment on high-level groupings of data structures used in the configuration and operation of the general use cases considered (e.g. HTTP routing, TLS termination, request authentication etc.). We will then assign a confidentiality, integrity and availability impact based on a worst-case scenario of how each compromise could potentially affect business data processed by the generic deployment.
Data Name / Type
Notes
Confidentiality
Integrity
Availability
Static Configuration Data
Static configuration data is used to configure Envoy Gateway at startup. This data structure allows for a Provider to be set, which Envoy Gateway calls to establish its runtime configuration, resolve services and persist data. Unauthorised modification of static configuration data could enable the Envoy Gateway admin interface to be configured, logging parameters to be modified, global rate limiting configuration to be misconfigured, or malicious extensions registered for the Envoy Gateway Control Plane. A compromise of confidentiality could potentially give an attacker some useful reconnaissance information. A compromise of the availability of this information at startup time would result in Envoy Gateway starting with default parameters.
Medium
High
Low
Dynamic Configuration Data
Dynamic configuration data represents the desired state of the Data Plane, and is defined through Envoy Gateway and Gateway API Kubernetes resources. Unauthorised modification of this data could lead to vulnerabilities in an organisation’s Data Plane infrastructure via misconfiguration of an EnvoyProxy custom resource. Specifically, the envoyDeployment.patch field in EnvoyProxy resources allows strategic/JSON merge patches over the full Deployment specification with insufficient validation, which could be exploited to inject dangerous configurations such as hostPath mounts, hostNetwork, hostPID, privileged containers, or arbitrary images and commands. This could enable privilege escalation from namespace-scoped access to node-root and cluster compromise. Misconfiguration of Gateway API objects such as HTTPRoutes or TLSRoutes could result in traffic being directed to incorrect backends. A compromise of confidentiality could potentially give an attacker some useful reconnaissance information. A compromise of the availability of this information could result in tenant application traffic not being routable until the configuration is recovered and reapplied.
Medium
High
Medium
TLS Private Keys
TLS Private Keys, typically in PEM format, are used to initiate secure connections and encrypt communications. In the context of this threat model, private keys will be associated with the server side of an inbound TLS connection being terminated at a secure gateway configured through Envoy Gateway. Unauthorised exposure could lead to security threats such as person-in-the-middle attacks, whereby the confidentiality or integrity of business data could be compromised. A compromise of integrity may lead to similar consequences if an attacker could insert their own key material. An availability compromise could lead to tenant services being unavailable until new key material is generated and an appropriate CSR submitted.
High
High
Medium
TLS Certificates
X.509 certificates represent the binding of a public key (associated with the private key described above) to an identity in a TLS handshake. If an attacker could compromise the integrity of a certificate, they may be able to bind the identity of a TLS termination point to a key pair under their control, enabling person-in-the middle attacks. An availability compromise could lead to tenant services being unavailable until new key material is generated and an appropriate CSR submitted.
Low
High
Medium
JWKs
JWK (JSON Web Key) containing a public key used to validate JWTs for the client authentication use case considered in this threat model. If an attacker could compromise the integrity of a JWK or JSON web key set (JWKS), they could potentially authenticate to a service maliciously. Unavailability of an endpoint exposing JWKs could lead to client requests which require authentication being denied.
Low
High
Medium
JWTs
JWTs, formatted as compact, URL-safe JSON data structures, are utilised for the client authentication use case considered in this threat model. Maintaining their confidentiality and integrity is vital to prevent unauthorised access and ensure correct user identification.
High
High
Low
OIDC credentials
In OIDC authentication scenarios, the application credentials are represented by a client ID and a client secret. A compromise of its confidentiality or integrity could allow malicious actors to impersonate the application, potentially being able to access resources on behalf of the application and request ID tokens on behalf of users. Unavailability of this data would produce a rejection of the requests coming from legitimate users.
High
High
Medium
Basic authentiation password hashes
In basic authentication scenarios, passwords are stored as Kubernetes secrets in htpasswd format, where each entry is formed by the username and the hashed password. A compromise of these credentials’ confidentiality and integrity could lead to unauthorised access to the application. Unavailability of these credentials will cause login failures from the application users.
High
High
Medium
CIA Impact Assessment
Priority
Description
Confidentiality
High
Compromise of sensitive client data
Medium
Information leaked which could be useful for attacker reconnaissance
Low
Non-sensitive information leakage
Integrity
High
Compromise of source code repositories and gateway deployments
Medium
Traffic routing fails due to misconfiguration / invalid configuration
Low
Non-critical operation is blocked due to misconfiguration / invalid configuration
Availability
High
Large scale DoS
Medium
Tenant application is blocked for a significant period
Low
Tenant application is blocked for a short period
Data Flow Diagrams
The Data Flow Diagrams (DFDs) below describe the flow of data between the various processes, entities and data stores in a system, as well as the trust boundaries between different user roles and network interfaces. The DFDs are drawn at two different levels, starting at L0 (high-level system view) and increasing in granularity (to L1).
DFD L0
DFD L1
Key Threats and Recommendations
The scope of this threat model led to us categorising threats into priorities of High, Medium or Low; notably in a production implementation some of the threats’ prioritisation may be upgraded or downgraded depending on the business context and data classification.
Risk vs. Threat
For every finding, the risk and threat are stated. Risk defines the potential for negative outcome while threat defines the event that causes the negative outcome.
Threat Categorization
Throughout this threat model, we categorised threats into different areas based on their origin and the segment of the system that they impact. Here’s an overview of each category:
Container Security (CS): These threats are general to containerised applications. Therefore, they are not associated with Envoy Gateway or the Gateway API and could occur in most containerised workloads. They can originate from misconfigurations or vulnerabilities in the orchestrator or the container.
Gateway API (GW): These are threats related to the Gateway API that could affect any of its implementations. Malicious actors could benefit from misconfigurations or excessive permissions on the Gateway API resources (e.g. xRoutes or Gateways) to compromise the confidentiality, integrity, or availability of the application.
Envoy Gateway (EG): These threats are associated with specific configurations or features from Envoy Gateway or Envoy Proxy. If not set properly, these features could be leveraged to gain unauthorised access to protected resources.
Threat Actors
In order to provide a realistic set of threats that is applicable to most organisations, we de-scoped the most advanced and hard to mitigate threat actors as described below:
In Scope Threat Actors
When considering internal threat actors, we chose to follow the security model of the Kubernetes Gateway API.
Internal Attacker
Cluster Operator: The cluster operator (ops) is responsible for administration of entire clusters. They manage policies, network access, application permissions.
Application Developer: The application developer (dev) is responsible for defining their application configuration (e.g. timeouts, request matching/filter) and Service composition (e.g. path routing to backends).
Application Administrator: The application admin has administrative access to some namespaces within a cluster, but not the cluster as a whole.
External Attacker
Vandal: Script kiddie, trespasser
Motivated Individual: Political activist, thief, terrorist
Organised Crime: Syndicates, state-affiliated groups
Out of Scope Threat Actors
External Actors
Infrastructure Provider: The infrastructure provider (infra) is responsible for the overall environment that the cluster(s) are operating in. Examples include: the cloud provider, or the PaaS provider in a company.
Cloud Service Insider: Employee, external contractor, temporary worker
Foreign Intelligence Services (FIS): Nation states
High Priority Findings
EGTM-001 Usage of self-signed certificates
ID
UID
Category
Priority
EGTM-001
EGTM-GW-001
Gateway API
High
Risk: Self-signed certificates (which do not comply with PKI best practices) could lead to unauthorised access to the private key associated with the certificate used for inbound TLS termination at Envoy Proxy, compromising the confidentiality and integrity of proxied traffic.
Threat: Compromise of the private key associated with the certificate used for inbound TLS terminating at Envoy Proxy.
Recommendation: The Envoy Gateway quickstart demonstrates how to set up a Secure Gateway using an example where a self-signed root certificate is created using openssl. As stated in the Envoy Gateway documentation, this is not a suitable configuration for Production usage. It is recommended that PKI best practices are followed, whereby certificates are signed by an Intermediary CA which sits underneath an organisational 'offline' Root CA.
PKI best practices should also apply to the management of client certificates when using mTLS. The Envoy Gateway mTLS task shows how to set up client certificates using self-signed certificates. In the same way as gateway certificates and, as mentioned in the documentation, this configuration should not be used in production environments.
EGTM-002 Private keys are stored as Kubernetes secrets
ID
UID
Category
Priority
EGTM-002
EGTM-CS-001
Container Security
High
Risk: There is a risk that a threat actor could compromise the Kubernetes secret containing the Envoy private key, allowing the attacker to decrypt Envoy Proxy traffic, compromising the confidentiality of proxied traffic.
Threat: Kubernetes secret containing the Envoy private key is compromised and used to decrypt proxied traffic.
Recommendation: Certificate management best practices mandate short-lived key material where practical, meaning that a mechanism for rotation of private keys and certificates is required, along with a way for certificates to be mounted into Envoy containers. If Kubernetes secrets are used, when a certificate expires, the associated secret must be updated, and Envoy containers must be redeployed. Instead of a manual configuration, it is recommended that cert-manager is used.
EGTM-004 Usage of ClusterRoles with wide permissions
ID
UID
Category
Priority
EGTM-004
EGTM-K8-002
Container Security
High
Risk: There is a risk that a threat actor could abuse misconfigured RBAC to access the Envoy Gateway ClusterRole (envoy-gateway-role) and use it to expose all secrets across the cluster, thus compromising the confidentiality and integrity of tenant data.
Threat: Compromised Envoy Gateway or misconfigured ClusterRoleBinding (envoy-gateway-rolebinding) to Envoy Gateway ClusterRole (envoy-gateway-role), provides access to resources and secrets in different namespaces.
Recommendation: Users should be aware that Envoy Gateway uses a ClusterRole (envoy-gateway-role) when deployed via the Helm chart, to allow management of Envoy Proxies across different namespaces. This ClusterRole is powerful and includes the ability to read secrets in namespaces which may not be within the purview of Envoy Gateway.
Kubernetes best-practices involve restriction of ClusterRoleBindings, with the use of RoleBindings where possible to limit access per namespace by specifying the namespace in metadata. Namespace isolation reduces the impact of compromise from cluster-scoped roles. Ideally, fine-grained K8s roles should be created per the principle of least privilege to ensure they have the minimum access necessary for role functions.
The pull request #1656 introduced the use of Roles and RoleBindings in namespaced mode. This feature can be leveraged to reduce the amount of permissions required by the Envoy Gateway.
EGTM-007 Misconfiguration of Envoy Gateway dynamic config
ID
UID
Category
Priority
EGTM-007
EGTM-EG-002
Envoy Gateway
High
Risk: There is a risk that a threat actor could exploit misconfigured Kubernetes RBAC to create or modify Gateway API resources with no business need, potentially leading to the compromise of the confidentiality, integrity, and availability of resources and traffic within the cluster.
Threat: Unauthorised creation or misconfiguration of Gateway API resources by a threat actor with cluster-scoped access.
Recommendation: Configure the apiGroup and resource fields in RBAC policies to restrict access to Gateway and GatewayClass resources. Enable namespace isolation by using the namespace field, preventing unauthorised access to gateways in other namespaces.
EGTM-026 Privilege escalation via EnvoyProxy deployment patch
ID
UID
Category
Priority
EGTM-026
EGTM-EG-009
Envoy Gateway
High
Risk: There is a risk that a tenant with RBAC permissions to create or modify EnvoyProxy resources in their namespace could exploit insufficient validation of the envoyDeployment.patch field to inject dangerous pod configurations (such as hostPath mounts, hostNetwork, hostPID, privileged containers, or arbitrary images/commands). Since the patched Deployment is applied by the controller service account into the controller namespace, this could lead to node-level privilege escalation and potential cluster compromise, affecting the confidentiality, integrity, and availability of all cluster resources.
Threat: Malicious tenant exploits EnvoyProxy custom resource patch capabilities to inject privileged configurations, escalate to node-root access, and compromise the entire cluster.
Recommendation: Restrict access to EnvoyProxy custom resources through strict RBAC policies. In multi-tenant environments, tenants should not have permissions to create or modify EnvoyProxy resources. If EnvoyProxy customization is required, implement one of the following mitigations:
Disable EnvoyGateway’s EnvoyProxyPatch runtime flag to globally block the patch field across all EnvoyProxy-managed Kubernetes resources (envoyDeployment, envoyDaemonSet, envoyService, envoyHpa, envoyPDB), regardless of which namespace or GatewayClass/Gateway the EnvoyProxy resource is sourced from. Any patch present on an EnvoyProxy is dropped at render time and surfaced as a Warning/PatchDisabled status condition on that EnvoyProxy, while the Gateway keeps being reconciled and serving traffic. This flag is enabled by default to preserve pre-existing behavior, so multi-tenant clusters where tenants can author their own EnvoyProxy resources should opt out explicitly:
runtimeFlags:disabled:- EnvoyProxyPatch
Deploy admission webhooks (such as OPA Gatekeeper or Kyverno) to validate EnvoyProxy resources and enforce an allowlist of permitted fields in the envoyDeployment.patch. Block dangerous configurations including hostPath, hostNetwork, hostPID, privileged, and container image overrides.
Use Pod Security Admission with enforced restricted or baseline standards on the controller namespace to prevent deployment of pods with elevated privileges.
Follow the recommended multi-tenancy model where each tenant deploys their own Envoy Gateway controller in a namespace they own, limiting the blast radius of any compromise.
Implement GitOps workflows where EnvoyProxy resources are managed centrally by cluster operators rather than by tenant developers, ensuring proper review and validation before deployment.
EGTM-009 Co-tenant misconfigures resource across namespaces
ID
UID
Category
Priority
EGTM-009
EGTM-GW-002
Gateway API
High
Risk: There is a risk that a co-tenant misconfigures Gateway or Route resources, compromising the confidentiality, integrity, and availability of routed traffic through Envoy Gateway.
Threat: Malicious or accidental co-tenant misconfiguration of Gateways and Routes associated with other application teams.
Recommendation: Dedicated Envoy Gateways should be provided to each tenant within their respective namespace. A one-to-one relationship should be established between GatewayClass and Gateway resources, meaning that each tenant namespace should have their own GatewayClass watched by a unique Envoy Gateway Controller as defined here in the Deployment Mode documentation.
Application Admins should have write permissions on the Gateway resource, but only in their specific namespaces, and Application Developers should only hold write permissions on Route resources. To enact this access control schema, follow the Write Permissions for Advanced 4 Tier Model described in the Kubernetes Gateway API security model. Examples of secured gateway-route topologies can be found here within the Kubernetes Gateway API docs.
Optionally, consider a GitOps model, where only the GitOps operator has the permission to deploy or modify custom resources in production.
EGTM-014 Malicious image admission
ID
UID
Category
Priority
EGTM-014
EGTM-CS-006
Container Security
High
Risk: There is a risk that a supply chain attack on Envoy Gateway results in an arbitrary compromise of the confidentiality, integrity or availability of tenant data.
Threat: Supply chain threat actor introduces malicious code into Envoy Gateway or Proxy.
Recommendation: The Envoy Gateway project should continue to work towards conformance with supply-chain security best practices throughout the project lifecycle (for example, as set out in the CNCF Software Supply Chain Best Practices Whitepaper). Adherence to Supply-chain Levels for Software Artefacts (SLSA) standards is crucial for maintaining the security of the system. Employ version control systems to monitor the source and build platforms and assign responsibility to a specific stakeholder.
Integrate a supply chain security tool such as Sigstore, which provides native capabilities for signing and verifying container images and software artefacts. Software Bill of Materials (SBOM), Vulnerability Exploitability eXchange (VEX), and signed artefacts should also be incorporated into the security protocol.
EGTM-020 Out of date or misconfigured Envoy Proxy image
ID
UID
Category
Priority
EGTM-020
EGTM-CS-009
Container Security
High
Risk: There is a risk that a threat actor exploits an Envoy Proxy vulnerability to remote code execution (RCE) due to out of date or misconfigured Envoy Proxy pod deployment, compromising the confidentiality and integrity of Envoy Proxy along with the availability of the proxy service.
Threat: Deployment of an Envoy Proxy or Gateway image containing exploitable CVEs.
Recommendation: Always use the latest version of the Envoy Proxy image. Regularly check for updates and patch the system as soon as updates become available. Implement a CI/CD pipeline that includes security checks for images and prevents deployment of insecure configurations. A suitable tool should be chosen to provide container vulnerability scanning to mitigate the risk of known vulnerabilities.
EGTM-022 Credentials are stored as Kubernetes Secrets
ID
UID
Category
Priority
EGTM-022
EGTM-CS-010
Container Security
High
Risk: There is a risk that the OIDC client secret (for OIDC authentication) and user password hashes (for basic authentication) get leaked due to misconfigured RBAC permissions.
Threat: Unauthorised access to the application due to credential leakage.
Recommendation: Ensure that only authorised users and service accounts are able to access secrets. This is especially important in namespaces where SecurityPolicy objects are configured, since those namespaces are the ones to store secrets containing the client secret (in OIDC scenarios) and user password hashes (in basic authentication scenarios).
To do so, minimise the use of ClusterRoles and Roles allowing listing and getting secrets. Perform periodic audits of RBAC permissions.
EGTM-023 Weak Authentication
ID
UID
Category
Priority
EGTM-023
EGTM-EG-007
Envoy Gateway
High
Risk: There is a risk of unauthorised access due to the use of basic authentication, which does not enforce any password restriction in terms of complexity and length. In addition, password hashes are stored in SHA1 format, which is a deprecated hashing function.
Threat: Unauthorised access to the application due to weak authentication mechanisms.
Recommendation: It is recommended to make use of stronger authentication mechanisms (i.e. JWT authentication and OIDC authentication) instead of basic authentication. These authentication mechanisms have many advantages, such as the use of short-lived credentials and a central management of security policies through the identity provider.
Medium Priority Findings
EGTM-008 Misconfiguration of Envoy Gateway static config
ID
UID
Category
Priority
EGTM-008
EGTM-EG-003
Envoy Gateway
Medium
Risk: There is a risk of a threat actor misconfiguring static config and compromising the integrity of Envoy Gateway, ultimately leading to the compromised confidentiality, integrity, or availability of tenant data and cluster resources.
Threat: Accidental or deliberate misconfiguration of static configuration leads to a misconfigured deployment of Envoy Gateway, for example logging parameters could be modified or global rate limiting configuration misconfigured.
Recommendation: Implement a GitOps model, utilising Kubernetes' Role-Based Access Control (RBAC) and adhering to the principle of least privilege to minimise human intervention on the cluster. For instance, tools like Flux and ArgoCD can be used for declarative GitOps deployments, ensuring all changes are tracked and reviewed. Additionally, configure your source control management (SCM) system to include mandatory pull request (PR) reviews, commit signing, and protected branches to ensure only authorised changes can be committed to the start-up configuration.
EGTM-010 Weak pod security contexts and policies
ID
UID
Category
Priority
EGTM-010
EGTM-CS-005
Container Security
Medium
Risk: There is a risk that a threat actor exploits a weak pod security context, compromising the CIA of a node and the resources / services which run on it.
Threat: Threat Actor who has compromised a pod exploits weak security context to escape to a node, potentially leading to the compromise of Envoy Proxy or Gateway running on the same node.
Recommendation: To mitigate this risk, apply Pod Security Standards at a minimum of Baseline level to all namespaces, especially those containing Envoy Gateway and Proxy Pods. Pod security standards are implemented through K8s Pod Security Admission to provide admission control modes (enforce, audit, and warn) for namespaces. Pod security standards can be enforced by namespace labels as shown here, to enforce a baseline level of pod security to specific namespaces.
Further enhance the security by implementing a sandboxing solution such as gVisor for Envoy Gateway and Proxy Pods to isolate the application from the host kernel. This can be set within the runtimeClassName of the Pod specification.
EGTM-012 ClusterRoles and Roles with permission to deploy ReferenceGrants
ID
UID
Category
Priority
EGTM-012
EGTM-GW-004
Gateway API
Medium
Risk: There is a risk that a threat actor could abuse excessive RBAC privileges to create ReferenceGrant resources. These resources could then be used to create cross-namespace communication, leading to unauthorised access to the application. This could compromise the confidentiality and integrity of resources and configuration in the affected namespaces and potentially disrupt the availability of services that rely on these object references.
Threat: A ReferenceGrant is created, which validates traffic to cross namespace trust boundaries without a valid business reason, such as a route in one tenant's namespace referencing a backend in another.
Recommendation: Ensure that the ability to create ReferenceGrant resources is restricted to the minimum number of people. Pay special attention to ClusterRoles that allow that action.
EGTM-018 Network Denial of Service (DoS)
ID
UID
Category
Priority
EGTM-018
EGTM-GW-006
Gateway API
Medium
Risk: There is a risk that malicious requests could lead to a Denial of Service (DoS) attack, thereby reducing API gateway availability due to misconfigurations in rate-limiting or load balancing controls, or a lack of route timeout enforcement.
Threat: Reduced API gateway availability due to an attacker's maliciously crafted request (e.g., QoD) potentially inducing a Denial of Service (DoS) attack.
Recommendation: To ensure high availability and mitigate potential security threats, follow the guidelines in the Envoy Gateway documentation for configuring local rate limit filters, global rate limit filters, and load balancing.
Path normalisation should be enabled to minimise path confusion vulnerabilities. These measures help protect against volumetric threats such as Denial of Service (DoS) attacks. Utilise custom resources to implement policy attachment, thereby exposing request limit configuration for route types.
EGTM-019 JWT-based authentication replay attacks
ID
UID
Category
Priority
EGTM-019
EGTM-DP-004
Container Security
Medium
Risk: There is a risk that replay attacks using stolen or reused JSON Web Tokens (JWTs) can compromise transmission integrity, thereby undermining the confidentiality and integrity of the data plane.
Threat: Transmission integrity is compromised due to replay attacks using stolen or reused JSON Web Tokens (JWTs).
Recommendation: Comply with JWT best practices for enhanced security, paying special attention to the use of short-lived tokens, which reduce the window of opportunity for a replay attack. The exp claim can be used to set token expiration times.
EGTM-024 Excessive privileges via extension policies
ID
UID
Category
Priority
EGTM-024
EGTM-EG-008
Envoy Gateway
Medium
Risk: There is a risk of developers getting more privileges than required due to the use of SecurityPolicy, ClientTrafficPolicy, EnvoyPatchPolicy and BackendTrafficPolicy. These resources can be attached to a Gateway resource. Therefore, a developer with permission to deploy them would be able to modify a Gateway configuration by targeting the gateway in the policy manifest. This conflicts with the Advanced 4 Tier Model, where developers do not have write permissions on Gateways.
Threat: Excessive developer permissions lead to a misconfiguration and/or unauthorised access.
Recommendation: Considering the Tenant C scenario (represented in the Architecture Diagram), if a developer can create SecurityPolicy, ClientTrafficPolicy, EnvoyPatchPolicy or BackendTrafficPolicy objects in namespace C, they would be able to modify a Gateway configuration by attaching the policy to the gateway. In such scenarios, it is recommended to either:
a. Create a separate namespace, where developers have no permissions, to host tenant C's gateway. Note that, due to design decisions, the SecurityPolicy/EnvoyPatchPolicy/ClientTrafficPolicy/BackendTrafficPolicy object can only target resources deployed in the same namespace. Therefore, having a separate namespace for the gateway would prevent developers from attaching the policy to the gateway.
b. Forbid the creation of these policies for developers in namespace C.
On the other hand, in scenarios similar to tenants A and B, where a shared gateway namespace is in place, this issue is more limited. Note that in this scenario, developers don't have access to the shared gateway namespace.
In addition, it is important to mention that EnvoyPatchPolicy resources can also be attached to GatewayClass resources. This means that, in order to comply with the Advanced 4 Tier model, individuals with the Application Administrator role should not have access to this resource either.
Low Priority Findings
EGTM-003 Misconfiguration leads to insecure TLS settings
ID
UID
Category
Priority
EGTM-003
EGTM-EG-001
Envoy Gateway
Low
Risk: There is a risk that a threat actor could downgrade the security of proxied connections by configuring a weak set of cipher suites, compromising the confidentiality and integrity of proxied traffic.
Threat: Exploit weak cipher suite configuration to downgrade security of proxied connections.
Recommendation: Users operating in highly regulated environments may need to tightly control the TLS protocol and associated cipher suites, blocking non-conforming incoming connections to the gateway.
EnvoyProxy bootstrap config can be customised as per the customise EnvoyProxy documentation. In addition, from v.1.0.0, it is possible to configure common TLS properties for a Gateway or XRoute through the ClientTrafficPolicy object.
EGTM-005 Envoy Gateway Helm chart deployment does not set AppArmor and Seccomp profiles
ID
UID
Category
Priority
EGTM-005
EGTM-CP-002
Container Security
Low
Risk: Threat actor who has obtained access to Envoy Gateway pod could exploit the lack of AppArmor and Seccomp profiles in the Envoy Gateway deployment to attempt a container breakout, given the presence of an exploitable vulnerability, potentially impacting the confidentiality and integrity node resources.
Threat: Unauthorised syscalls and malicious code running in the Envoy Gateway pod.
Recommendation: Implement AppArmor policies by setting <container_name>: <profile_ref> within container.apparmor.security.beta.kubernetes.io (note, this config is set per container). Well-defined AppArmor policies may provide greater protection from unknown threats.
Enforce Seccomp profiles by setting the seccompProfile under securityContext. Ideally, a fine-grained profile should be used to restrict access to only necessary syscalls, however the --seccomp-default flag can be set to resort to RuntimeDefault which provides a container runtime specific. Example seccomp profiles can be found here.
To further enhance pod security, consider implementing SELinux via seLinuxOptions for additional syscall attack surface reduction. Setting readOnlyRootFilesystem == true enforces an immutable root filesystem, preventing the addition of malicious binaries to the PATH and increasing the attack cost. Together, these configuration items improve the pods Security Context.
EGTM-006 Envoy Proxy pods deployed with a shell enabled
ID
UID
Category
Priority
EGTM-006
EGTM-CS-004
Container Security
Low
Risk: There is a risk that a threat actor exploits a vulnerability in Envoy Proxy to expose a reverse shell, enabling them to compromise the confidentiality, integrity and availability of tenant data via a secondary attack.
Threat: If an external attacker managed to exploit a vulnerability in Envoy, the presence of a shell would be greatly helpful for the attacker in terms of potentially pivoting, escalating, or establishing some form of persistence.
Recommendation: By default, Envoy uses a distroless image since v.0.6.0, which does not ship a shell. Therefore, ensure EnvoyProxy image is up-to-date and patched with the latest stable version.
If using private EnvoyProxy images, use a lightweight EnvoyProxy image without a shell or debugging tool(s) which may be useful for an attacker.
An AuditPolicy (audit.k8s.io/v1beta1) can be configured to record API calls made within your cluster, allowing for identification of malicious traffic and enabling incident response. Requests are recorded based on stages which delineate between the lifecycle stage of the request made (e.g., RequestReceived, ResponseStarted, & ResponseComplete).
EGTM-011 Route Bindings on custom labels
ID
UID
Category
Priority
EGTM-011
EGTM-GW-003
Gateway API
Low
Risk: There is a risk that a gateway owner (or someone with the ability to set namespace labels) maliciously or accidentally binds routes across namespace boundaries, potentially compromising the confidentiality and integrity of traffic in a multitenant scenario.
Threat: If a Route Binding within a Gateway Listener is configured based on a custom label, it could allow a malicious internal actor with the ability to label namespaces to change the set of namespaces supported by the Gateway.
Recommendation: Consider the use of custom admission control to restrict what labels can be set on namespaces through tooling such as Kubewarden, Kyverno, and OPA Gatekeeper. Route binding should follow the Kubernetes Gateway API security model, as shown here, to connect gateways in different namespaces.
EGTM-013 GatewayClass namespace validation is not configured
ID
UID
Category
Priority
EGTM-013
EGTM-GW-005
Gateway API
Low
Risk: There is a risk that an unauthorised actor deploys an unauthorised GatewayClass due to GatewayClass namespace validation not being configured, leading to non-compliance with business and security requirements.
Threat: Unauthorised deployment of Gateway resource via GatewayClass template which crosses namespace trust boundaries.
Recommendation: Leverage GatewayClass namespace validation to limit the namespaces where GatewayClasses can be run through a tool such as OPA Gatekeeper. Reference pull request #24 within gatekeeper-library which outlines how to add GatewayClass namespace validation through a GatewayClassNamespaces API resource kind within the constraints.gatekeeper.sh/v1beta1 apiGroup.
EGTM-015 ServiceAccount token authentication
ID
UID
Category
Priority
EGTM-015
EGTM-CS-007
Container Security
Low
Risk: There is a risk that threat actors could exploit ServiceAccount tokens for illegitimate authentication, thereby leading to privilege escalation and the undermining of gateway API resources' integrity, confidentiality, and availability.
Threat: The threat arises from threat actors impersonating the envoy-gateway ServiceAccount through the replay of ServiceAccount tokens, thereby achieving escalated privileges and gaining unauthorised access to Kubernetes resources.
Recommendation: Limit the creation of ServiceAccounts to only when necessary, specifically refraining from using default service account tokens, especially for high-privilege service accounts. For legacy clusters running Kubernetes version 1.21 or earlier, note that ServiceAccount tokens are long-lived by default. To disable the automatic mounting of the service account token, set automountServiceAccountToken: false in the PodSpec.
EGTM-016 Misconfiguration leads to lack of Envoy Proxy access activity visibility
ID
UID
Category
Priority
EGTM-016
EGTM-EG-004
Envoy Gateway
Low
Risk: There is a risk that threat actors establish persistence and move laterally through the cluster unnoticed due to limited visibility into access and application-level activity.
Threat: Threat actors establish persistence and move laterally through the cluster unnoticed.
Additionally, consider leveraging a central logging mechanism such as Fluentd to enhance visibility into access activity and enable effective incident response (IR).
EGTM-017 Misconfiguration leads to lack of Envoy Gateway activity visibility
ID
UID
Category
Priority
EGTM-017
EGTM-EG-005
Envoy Gateway
Low
Risk: There is a risk that an insider misconfigures an envoy gateway component and goes unnoticed due to a low-touch logging configuration (via default) which responsible stakeholders are not aptly aware of or have immediate access to.
Threat: The threat emerges from an insider misconfiguring an Envoy Gateway component without detection.
Recommendation: Configure the logging level of the Envoy Gateway using the 'level' field in EnvoyGatewayLogging. Ensure the appropriate logging levels are set for relevant components such as 'gateway-api', 'xds-translator', or 'global-ratelimit'. If left unspecified, the logging level defaults to "info", which may not provide sufficient detail for security monitoring.
Employ a centralised logging mechanism, like Fluentd, to enhance visibility into application-level activity and to enable efficient incident response.
EGTM-021 Exposed Envoy Proxy admin interface
ID
UID
Category
Priority
EGTM-021
EGTM-EG-006
Envoy Gateway
Low
Risk: There is a risk that the admin interface is exposed without valid business reason, increasing the attack surface.
Threat: Exposed admin interfaces give internal attackers the option to affect production traffic in unauthorised ways, and the option to exploit any vulnerabilities which may be present in the admin interface (e.g. by orchestrating malicious GET requests to the admin interface through CSRF, compromising Envoy Proxy global configuration or shutting off the service entirely e.g. /quitquitquit).
Recommendation: The Envoy Proxy admin interface is only exposed to localhost, meaning that it is secure by default. However, due to the risk of misconfiguration, this recommendation is included.
Due to the importance of the admin interface, it is recommended to ensure that Envoy Proxies have not been accidentally misconfigured to expose the admin interface to untrusted networks.
EGTM-025 Envoy Proxy pods deployed running as root user in the container
ID
UID
Category
Priority
EGTM-025
EGTM-CS-011
Container Security
Low
Risk: The presence of a vulnerability, be it in the kernel or another system component, when coupled with containers running as root, could enable a threat actor to escape the container, thereby compromising the confidentiality, integrity, or availability of cluster resources
Threat: The Envoy Proxy container’s root-user configuration can be leveraged by an attacker to escalate privileges, execute a container breakout, and traverse across trust boundaries.
Recommendation: By default, Envoy Gateway deployments do not use root users. Nonetheless, in case a custom image or deployment manifest is to be used, make sure Envoy Proxy pods run as a non-root user with a high UID within the container.
Set runAsUser and runAsGroup security context options to specific UIDs (e.g., runAsUser: 1000 & runAsGroup: 3000) to ensure the container operates with the stipulated non-root user and group ID. If using helm chart deployment, define the user and group ID in the values.yaml file or via the command line during helm install / upgrade.
Appendix
In Scope Threat Actor Details
Threat Actor
Capability
Personal Motivation
Envoy Gateway Attack Samples
Application Developer
Leverage internal knowledge and personal access to the Envoy Gateway infrastructure to move laterally and transit trust boundaries
Disgruntled / personal grievances.
Financial incentives
Misconfigure XRoute resources to expose internal applications.
Misconfigure SecurityPolicy objects, reducing the security posture of an application.
Application Administrator
Abuse privileged status to disrupt operations and tenant cluster services through Envoy Gateway misconfig
Disgruntled / personal grievances.
Financial incentives
Create malicious routes to internal applications.
Introduce malicious Envoy Proxy images.
Expose the Envoy Proxy Admin interface.
Cluster Operator
Alter application-level deployments by misconfiguring resource dependencies & SCM to introduce vulnerabilities
Disgruntled / personal grievances.
Financial incentives.
Notoriety
Deploy malicious resources to expose internal applications.
Access authentication secrets.
Fall victim to phishing attacks and inadvertently share authentication credentials to cloud infrastructure or Kubernetes clusters.
Vandal: Script Kiddie, Trespasser
Uses publicly available tools and applications (Nmap,Metasploit, CVE PoCs)
Curiosity.
Personal fame through defacement / denial of service of prominent public facing web resources
Exploit public-facing application services such as the bastion host to gain an initial foothold in the environment
Motivated individual: Political activist, Thief, Terrorist
Write tools and exploits required for their means if sufficiently motivated.
Tend to use these in a targeted fashion against specific organisations. May combine publicly available exploits in a targeted fashion. Tamper with open source supply chains
Personal Gain (Political or Ideological)
Phishing, DDOS, exploit known vulnerabilities.
Compromise third-party components such as Helm charts and container images to inject malicious codes to propagate access throughout the environment.
Organised crime: syndicates, state-affiliated groups
Write tools and exploits required for their means.
Tend to use these in a non-targeted fashion, unless motivation is sufficiently high.
Devotes considerable resources, writes exploits, can bribe/coerce, can launch targeted attacks
Ransom.
Mass extraction of PII / credentials / PCI data.
Financial incentives
Social Engineering, phishing, ransomware, coordinated attacks.
Intercept and replay JWT tokens (via MiTM) between tenant user(s) and envoy gateway to modify app configs in-transit
Identified Threats by Priority
ID
UID
Category
Risk
Threat
Priority
Recommendation
EGTM-001
EGTM-GW-001
Gateway API
Self-signed certificates (which do not comply with PKI best practices) could lead to unauthorised access to the private key associated with the certificate used for inbound TLS termination at Envoy Proxy, compromising the confidentiality and integrity of proxied traffic.
Compromise of the private key associated with the certificate used for inbound TLS terminating at Envoy Proxy.
High
The Envoy Gateway quickstart demonstrates how to set up a Secure Gateway using an example where a self-signed root certificate is created using openssl. As stated in the Envoy Gateway documentation, this is not a suitable configuration for Production usage. It is recommended that PKI best practices are followed, whereby certificates are signed by an Intermediary CA which sits underneath an organisational 'offline' Root CA.
PKI best practices should also apply to the management of client certificates when using mTLS. The Envoy Gateway mTLS task shows how to set up client certificates using self-signed certificates. In the same way as gateway certificates and, as mentioned in the documentation, this configuration should not be used in production environments.
EGTM-002
EGTM-CS-001
Container Security
There is a risk that a threat actor could compromise the Kubernetes secret containing the Envoy private key, allowing the attacker to decrypt Envoy Proxy traffic, compromising the confidentiality of proxied traffic.
Kubernetes secret containing the Envoy private key is compromised and used to decrypt proxied traffic.
High
Certificate management best practices mandate short-lived key material where practical, meaning that a mechanism for rotation of private keys and certificates is required, along with a way for certificates to be mounted into Envoy containers. If Kubernetes secrets are used, when a certificate expires, the associated secret must be updated, and Envoy containers must be redeployed. Instead of a manual configuration, it is recommended that cert-manager is used.
EGTM-004
EGTM-K8-002
Container Security
There is a risk that a threat actor could abuse misconfigured RBAC to access the Envoy Gateway ClusterRole (envoy-gateway-role) and use it to expose all secrets across the cluster, thus compromising the confidentiality and integrity of tenant data.
Compromised Envoy Gateway or misconfigured ClusterRoleBinding (envoy-gateway-rolebinding) to Envoy Gateway ClusterRole (envoy-gateway-role), provides access to resources and secrets in different namespaces.
High
Users should be aware that Envoy Gateway uses a ClusterRole (envoy-gateway-role) when deployed via the Helm chart, to allow management of Envoy Proxies across different namespaces. This ClusterRole is powerful and includes the ability to read secrets in namespaces which may not be within the purview of Envoy Gateway.
Kubernetes best-practices involve restriction of ClusterRoleBindings, with the use of RoleBindings where possible to limit access per namespace by specifying the namespace in metadata. Namespace isolation reduces the impact of compromise from cluster-scoped roles. Ideally, fine-grained K8s roles should be created per the principle of least privilege to ensure they have the minimum access necessary for role functions.
The pull request #1656 introduced the use of Roles and RoleBindings in namespaced mode. This feature can be leveraged to reduce the amount of permissions required by the Envoy Gateway.
EGTM-007
EGTM-EG-002
Envoy Gateway
There is a risk that a threat actor could exploit misconfigured Kubernetes RBAC to create or modify Gateway API resources with no business need, potentially leading to the compromise of the confidentiality, integrity, and availability of resources and traffic within the cluster.
Unauthorised creation or misconfiguration of Gateway API resources by a threat actor with cluster-scoped access.
High
Configure the apiGroup and resource fields in RBAC policies to restrict access to Gateway and GatewayClass resources. Enable namespace isolation by using the namespace field, preventing unauthorised access to gateways in other namespaces.
EGTM-009
EGTM-GW-002
Gateway API
There is a risk that a co-tenant misconfigures Gateway or Route resources, compromising the confidentiality, integrity, and availability of routed traffic through Envoy Gateway.
Malicious or accidental co-tenant misconfiguration of Gateways and Routes associated with other application teams.
High
Dedicated Envoy Gateways should be provided to each tenant within their respective namespace. A one-to-one relationship should be established between GatewayClass and Gateway resources, meaning that each tenant namespace should have their own GatewayClass watched by a unique Envoy Gateway Controller as defined here in the Deployment Mode documentation.
Application Admins should have write permissions on the Gateway resource, but only in their specific namespaces, and Application Developers should only hold write permissions on Route resources. To enact this access control schema, follow the Write Permissions for Advanced 4 Tier Model described in the Kubernetes Gateway API security model. Examples of secured gateway-route topologies can be found here within the Kubernetes Gateway API docs.
Optionally, consider a GitOps model, where only the GitOps operator has the permission to deploy or modify custom resources in production.
EGTM-014
EGTM-CS-006
Container Security
There is a risk that a supply chain attack on Envoy Gateway results in an arbitrary compromise of the confidentiality, integrity or availability of tenant data.
Supply chain threat actor introduces malicious code into Envoy Gateway or Proxy.
High
The Envoy Gateway project should continue to work towards conformance with supply-chain security best practices throughout the project lifecycle (for example, as set out in the CNCF Software Supply Chain Best Practices Whitepaper. Adherence to Supply-chain Levels for Software Artefacts (SLSA) standards is crucial for maintaining the security of the system. Employ version control systems to monitor the source and build platforms and assign responsibility to a specific stakeholder.
Integrate a supply chain security tool such as Sigstore, which provides native capabilities for signing and verifying container images and software artefacts. Software Bill of Materials (SBOM), Vulnerability Exploitability eXchange (VEX), and signed artefacts should also be incorporated into the security protocol.
EGTM-020
EGTM-CS-009
Container Security
There is a risk that a threat actor exploits an Envoy Proxy vulnerability to remote code execution (RCE) due to out of date or misconfigured Envoy Proxy pod deployment, compromising the confidentiality and integrity of Envoy Proxy along with the availability of the proxy service.
Deployment of an Envoy Proxy or Gateway image containing exploitable CVEs.
High
Always use the latest version of the Envoy Proxy image. Regularly check for updates and patch the system as soon as updates become available. Implement a CI/CD pipeline that includes security checks for images and prevents deployment of insecure configurations. A tool such as Snyk can be used to provide container vulnerability scanning to mitigate the risk of known vulnerabilities.
There is a risk that the OIDC client secret (for OIDC authentication) and user password hashes (for basic authentication) get leaked due to misconfigured RBAC permissions.
Unauthorised access to the application due to credential leakage.
High
Ensure that only authorised users and service accounts are able to access secrets. This is especially important in namespaces where SecurityPolicy objects are configured, since those namespaces are the ones to store secrets containing the client secret (in OIDC scenarios) and user password hashes (in basic authentication scenarios).
To do so, minimise the use of ClusterRoles and Roles allowing listing and getting secrets. Perform periodic audits of RBAC permissions.
EGTM-023
EGTM-EG-007
Envoy Gateway
There is a risk of unauthorised access due to the use of basic authentication, which does not enforce any password restriction in terms of complexity and length. In addition, password hashes are stored in SHA1 format, which is a deprecated hashing function.
Unauthorised access to the application due to weak authentication mechanisms.
High
It is recommended to make use of stronger authentication mechanisms (i.e. JWT authentication and OIDC authentication) instead of basic authentication. These authentication mechanisms have many advantages, such as the use of short-lived credentials and a central management of security policies through the identity provider.
EGTM-008
EGTM-EG-003
Envoy Gateway
There is a risk of a threat actor misconfiguring static config and compromising the integrity of Envoy Gateway, ultimately leading to the compromised confidentiality, integrity, or availability of tenant data and cluster resources.
Accidental or deliberate misconfiguration of static configuration leads to a misconfigured deployment of Envoy Gateway, for example logging parameters could be modified or global rate limiting configuration misconfigured.
Medium
Implement a GitOps model, utilising Kubernetes' Role-Based Access Control (RBAC) and adhering to the principle of least privilege to minimise human intervention on the cluster. For instance, tools like Flux and ArgoCD can be used for declarative GitOps deployments, ensuring all changes are tracked and reviewed. Additionally, configure your source control management (SCM) system to include mandatory pull request (PR) reviews, commit signing, and protected branches to ensure only authorised changes can be committed to the start-up configuration.
EGTM-010
EGTM-CS-005
Container Security
There is a risk that a threat actor exploits a weak pod security context, compromising the CIA of a node and the resources / services which run on it.
Threat Actor who has compromised a pod exploits weak security context to escape to a node, potentially leading to the compromise of Envoy Proxy or Gateway running on the same node.
Medium
To mitigate this risk, apply Pod Security Standards at a minimum of Baseline level to all namespaces, especially those containing Envoy Gateway and Proxy Pods. Pod security standards are implemented through K8s Pod Security Admission to provide admission control modes (enforce, audit, and warn) for namespaces. Pod security standards can be enforced by namespace labels as shown here, to enforce a baseline level of pod security to specific namespaces.
Further enhance the security by implementing a sandboxing solution such as gVisor for Envoy Gateway and Proxy Pods to isolate the application from the host kernel. This can be set within the runtimeClassName of the Pod specification.
EGTM-012
EGTM-GW-004
Gateway API
There is a risk that a threat actor could abuse excessive RBAC privileges to create ReferenceGrant resources. These resources could then be used to create cross-namespace communication, leading to unauthorised access to the application. This could compromise the confidentiality and integrity of resources and configuration in the affected namespaces and potentially disrupt the availability of services that rely on these object references.
A ReferenceGrant is created, which validates traffic to cross namespace trust boundaries without a valid business reason, such as a route in one tenant's namespace referencing a backend in another.
Medium
Ensure that the ability to create ReferenceGrant resources is restricted to the minimum number of people. Pay special attention to ClusterRoles that allow that action.
EGTM-018
EGTM-GW-006
Gateway API
There is a risk that malicious requests could lead to a Denial of Service (DoS) attack, thereby reducing API gateway availability due to misconfigurations in rate-limiting or load balancing controls, or a lack of route timeout enforcement.
Reduced API gateway availability due to an attacker's maliciously crafted request (e.g., QoD) potentially inducing a Denial of Service (DoS) attack.
Medium
To ensure high availability and to mitigate potential security threats, adhere to the Envoy Gateway documentation for the configuration of a rate-limiting filter and load balancing.
Path normalisation should be enabled to minimise path confusion vulnerabilities. These measures help protect against volumetric threats such as Denial of Service (DoS)nattacks. Utilise custom resources to implement policy attachment, thereby exposing request limit configuration for route types.
EGTM-019
EGTM-DP-004
Container Security
There is a risk that replay attacks using stolen or reused JSON Web Tokens (JWTs) can compromise transmission integrity, thereby undermining the confidentiality and integrity of the data plane.
Transmission integrity is compromised due to replay attacks using stolen or reused JSON Web Tokens (JWTs).
Medium
Comply with JWT best practices for enhanced security, paying special attention to the use of short-lived tokens, which reduce the window of opportunity for a replay attack. The exp claim can be used to set token expiration times.
EGTM-024
EGTM-EG-008
Envoy Gateway
There is a risk of developers getting more privileges than required due to the use of SecurityPolicy, ClientTrafficPolicy, EnvoyPatchPolicy and BackendTrafficPolicy. These resources can be attached to a Gateway resource. Therefore, a developer with permission to deploy them would be able to modify a Gateway configuration by targeting the gateway in the policy manifest. This conflicts with the Advanced 4 Tier Model, where developers do not have write permissions on Gateways.
Excessive developer permissions lead to a misconfiguration and/or unauthorised access.
Medium
Considering the Tenant C scenario (represented in the Architecture Diagram), if a developer can create SecurityPolicy, ClientTrafficPolicy, EnvoyPatchPolicy or BackendTrafficPolicy objects in namespace C, they would be able to modify a Gateway configuration by attaching the policy to the gateway. In such scenarios, it is recommended to either:
a. Create a separate namespace, where developers have no permissions, > to host tenant C's gateway. Note that, due to design decisions, > the > SecurityPolicy/EnvoyPatchPolicy/ClientTrafficPolicy/BackendTrafficPolicy > object can only target resources deployed in the same namespace. > Therefore, having a separate namespace for the gateway would > prevent developers from attaching the policy to the gateway.
b. Forbid the creation of these policies for developers in namespace C.
On the other hand, in scenarios similar to tenants A and B, where a shared gateway namespace is in place, this issue is more limited. Note that in this scenario, developers don't have access to the shared gateway namespace.
In addition, it is important to mention that EnvoyPatchPolicy resources can also be attached to GatewayClass resources. This means that, in order to comply with the Advanced 4 Tier model, individuals with the Application Administrator role should not have access to this resource either.
EGTM-003
EGTM-EG-001
Envoy Gateway
There is a risk that a threat actor could downgrade the security of proxied connections by configuring a weak set of cipher suites, compromising the confidentiality and integrity of proxied traffic.
Exploit weak cipher suite configuration to downgrade security of proxied connections.
Low
Users operating in highly regulated environments may need to tightly control the TLS protocol and associated cipher suites, blocking non-conforming incoming connections to the gateway.
EnvoyProxy bootstrap config can be customised as per the customise EnvoyProxy documentation. In addition, from v.1.0.0, it is possible to configure common TLS properties for a Gateway or XRoute through the ClientTrafficPolicy object.
EGTM-005
EGTM-CP-002
Container Security
Threat actor who has obtained access to Envoy Gateway pod could exploit the lack of AppArmor and Seccomp profiles in the Envoy Gateway deployment to attempt a container breakout, given the presence of an exploitable vulnerability, potentially impacting the confidentiality and integrity of namespace resources.
Unauthorised syscalls and malicious code running in the Envoy Gateway pod.
Low
Implement AppArmor policies by setting <container_name>: <profile_ref> within container.apparmor.security.beta.kubernetes.io (note, this config is set per container). Well-defined AppArmor policies may provide greater protection from unknown threats.
Enforce Seccomp profiles by setting the seccompProfile under securityContext. Ideally, a fine-grained profile should be used to restrict access to only necessary syscalls, however the --seccomp-default flag can be set to resort to RuntimeDefault which provides a container runtime specific. Example seccomp profiles can be found here.
To further enhance pod security, consider implementing SELinux via seLinuxOptions for additional syscall attack surface reduction. Setting readOnlyRootFilesystem == true enforces an immutable root filesystem, preventing the addition of malicious binaries to the PATH and increasing the attack cost. Together, these configuration items improve the pods Security Context.
EGTM-006
EGTM-CS-004
Container Security
There is a risk that a threat actor exploits a vulnerability in Envoy Proxy to expose a reverse shell, enabling them to compromise the confidentiality, integrity and availability of tenant data via a secondary attack.
If an external attacker managed to exploit a vulnerability in Envoy, the presence of a shell would be greatly helpful for the attacker in terms of potentially pivoting, escalating, or establishing some form of persistence.
Low
By default, Envoy uses a distroless image since v.0.6.0, which does not ship a shell. Therefore, ensure EnvoyProxy image is up-to-date and patched with the latest stable version.
If using private EnvoyProxy images, use a lightweight EnvoyProxy image without a shell or debugging tool(s) which may be useful for an attacker.
An AuditPolicy (audit.k8s.io/v1beta1) can be configured to record API calls made within your cluster, allowing for identification of malicious traffic and enabling incident response. Requests are recorded based on stages which delineate between the lifecycle stage of the request made (e.g., RequestReceived, ResponseStarted, & ResponseComplete).
EGTM-011
EGTM-GW-003
Gateway API
There is a risk that a gateway owner (or someone with the ability to set namespace labels) maliciously or accidentally binds routes across namespace boundaries, potentially compromising the confidentiality and integrity of traffic in a multitenant scenario.
If a Route Binding within a Gateway Listener is configured based on a custom label, it could allow a malicious internal actor with the ability to label namespaces to change the set of namespaces supported by the Gateway
Low
Consider the use of custom admission control to restrict what labels can be set on namespaces through tooling such as Kubewarden, Kyverno, and OPA Gatekeeper. Route binding should follow the Kubernetes Gateway API security model, as shown here, to connect gateways in different namespaces.
EGTM-013
EGTM-GW-005
Gateway API
There is a risk that an unauthorised actor deploys an unauthorised GatewayClass due to GatewayClass namespace validation not being configured, leading to non-compliance with business and security requirements.
Unauthorised deployment of Gateway resource via GatewayClass template which crosses namespace trust boundaries.
Low
Leverage GatewayClass namespace validation to limit the namespaces where GatewayClasses can be run through a tool such as using OPA Gatekeeper. Reference pull request #24 within gatekeeper-library which outlines how to add GatewayClass namespace validation through a GatewayClassNamespaces API resource kind within the constraints.gatekeeper.sh/v1beta1 apiGroup.
EGTM-015
EGTM-CS-007
Container Security
There is a risk that threat actors could exploit ServiceAccount tokens for illegitimate authentication, thereby leading to privilege escalation and the undermining of gateway API resources' integrity, confidentiality, and availability.
The threat arises from threat actors impersonating the envoy-gateway ServiceAccount through the replay of ServiceAccount tokens, thereby achieving escalated privileges and gaining unauthorised access to Kubernetes resources.
Low
Limit the creation of ServiceAccounts to only when necessary, specifically refraining from using default service account tokens, especially for high-privilege service accounts. For legacy clusters running Kubernetes version 1.21 or earlier, note that ServiceAccount tokens are long-lived by default. To disable the automatic mounting of the service account token, set automountServiceAccountToken: false in the PodSpec.
EGTM-016
EGTM-EG-004
Envoy Gateway
There is a risk that threat actors establish persistence and move laterally through the cluster unnoticed due to limited visibility into access and application-level activity.
Threat actors establish persistence and move laterally through the cluster unnoticed.
Additionally, consider leveraging a central logging mechanism such as Fluentd to enhance visibility into access activity and enable effective incident response (IR).
EGTM-017
EGTM-EG-005
Envoy Gateway
There is a risk that an insider misconfigures an envoy gateway component and goes unnoticed due to a low-touch logging configuration (via default) which responsible stakeholders are not aptly aware of or have immediate access to.
The threat emerges from an insider misconfiguring an Envoy Gateway component without detection.
Low
Configure the logging level of the Envoy Gateway using the 'level' field in EnvoyGatewayLogging. Ensure the appropriate logging levels are set for relevant components such as 'gateway-api', 'xds-translator', or 'global-ratelimit'. If left unspecified, the logging level defaults to "info", which may not provide sufficient detail for security monitoring.
Employ a centralised logging mechanism, like Fluentd, to enhance visibility into application-level activity and to enable efficient incident response.
EGTM-021
EGTM-EG-006
Envoy Gateway
There is a risk that the admin interface is exposed without valid business reason, increasing the attack surface.
Exposed admin interfaces give internal attackers the option to affect production traffic in unauthorised ways, and the option to exploit any vulnerabilities which may be present in the admin interface (e.g. by orchestrating malicious GET requests to the admin interface through CSRF, compromising Envoy Proxy global configuration or shutting off the service entirely (e.g., /quitquitquit).
Low
The Envoy Proxy admin interface is only exposed to localhost, meaning that it is secure by default. However, due to the risk of misconfiguration, this recommendation is included.
Due to the importance of the admin interface, it is recommended to ensure that Envoy Proxies have not been accidentally misconfigured to expose the admin interface to untrusted networks.
EGTM-025
EGTM-CS-011
Container Security
The presence of a vulnerability, be it in the kernel or another system component, when coupled with containers running as root, could enable a threat actor to escape the container, thereby compromising the confidentiality, integrity, or availability of cluster resources.
The Envoy Proxy container’s root-user configuration can be leveraged by an attacker to escalate privileges, execute a container breakout, and traverse across trust boundaries.
Low
By default, Envoy Gateway deployments do not use root users. Nonetheless, in case a custom image or deployment manifest is to be used, make sure Envoy Proxy pods run as a non-root user with a high UID within the container. Set runAsUser and runAsGroup security context options to specific UIDs (e.g., runAsUser: 1000 & runAsGroup: 3000) to ensure the container operates with the stipulated non-root user and group ID. If using helm chart deployment, define the user and group ID in the values.yaml file or via the command line during helm install / upgrade.
Attack Trees
Attack trees offer a methodical way of describing the security of systems, based on varying attack patterns. It’s important to approach the review of attack trees from a top-down perspective. The top node, also known as the root node, symbolises the attacker’s primary objective. This goal is then broken down into subsidiary aims, each reflecting a different strategy to attain the root objective. This deconstruction persists until reaching the lowest level objectives or ’leaf nodes’, which depict attacks that can be directly launched.
It is essential to note that attack trees presented here are speculative paths for potential exploitation. The Envoy Gateway project is in a continuous development cycle, and as the project evolves, new vulnerabilities may be exposed, or additional controls could be introduced. Therefore, the threats illustrated in the attack trees should be perceived as point-in-time reflections of the project’s current state at the time of writing this threat model.
Node ID Schema
Each node in the attack tree is assigned a unique identifier following the AT#-## schema. This allows easy reference to specific nodes in the attack trees throughout the threat model. The first part of the ID (AT#) signifies the attack tree number, while the second part (##) represents the node number within that tree.
Logical Operators
Logical AND/OR operators are used to represent the relationship between parent and child nodes. An AND operator means that all child nodes must be achieved to satisfy the parent node. An OR operator between a parent node and its child nodes means that any of the child nodes can be achieved to satisfy the parent node.
Attack Tree Node Legend
AT0
AT1
AT2
AT3
AT4
AT5
AT6
2.3.21 - TLS Passthrough
This task will walk through the steps required to configure TLS Passthrough via Envoy Gateway. Unlike configuring
Secure Gateways, where the Gateway terminates the client TLS connection, TLS Passthrough allows the application itself
to terminate the TLS connection, while the Gateway routes the requests to the application based on SNI headers.
Prerequisites
OpenSSL to generate TLS assets.
Installation
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
TLS Certificates
Generate the certificates and keys used by the Service to terminate client TLS connections.
For the application, we’ll deploy a sample echoserver app, with the certificates loaded in the application Pod.
Note: These certificates will not be used by the Gateway, but will remain in the application scope.
Create a root certificate and private key to sign certificates:
Follow the steps from the Quickstart to uninstall Envoy Gateway and the example manifest.
Delete the Secret:
kubectl delete secret/server-certs
Next Steps
Checkout the Developer Guide to get involved in the project.
2.3.22 - TLS Termination for TCP
This task walks through configuring TLS Terminate mode for TCP traffic via Envoy Gateway. For HTTPS termination on an HTTP listener (TLS + HTTPRoute), see the Secure Gateways task instead.
In both patterns below, Envoy terminates the client TLS connection on a TLS listener and forwards the decrypted bytes to a backend Service over plain TCP. The difference is how the listener selects a backend:
Single backend with TCPRoute — every connection accepted on the listener goes to one backend Service. TCPRoute does not inspect SNI, so each backend needs its own listener.
SNI-based routing with TLSRoute — one listener fans out to multiple backends, dispatched by the client’s SNI. Many TLSRoutes can attach to the same listener, so you avoid the listener-per-backend explosion.
TLSRoute itself works with both listener TLS modes: this task covers Terminate (Envoy decrypts and forwards plain TCP); for Passthrough (Envoy SNI-routes the still-encrypted bytes, leaving termination to the backend) see the TLS Passthrough task.
This task uses a self-signed CA, so it should be used for testing and demonstration purposes only.
Prerequisites
OpenSSL to generate TLS assets.
Installation
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Single Backend with TCPRoute
This section configures a TLS listener that terminates TLS for www.example.com and forwards the decrypted bytes to a single backend Service via a TCPRoute. Because TCPRoute does not match on SNI, this listener can only serve one backend — additional backends would each need their own listener.
TLS Certificates
Generate the certificates and keys used by the Gateway to terminate client TLS connections.
Create a root certificate and private key to sign certificates:
This section configures a single TLS listener that terminates TLS for *.example.com and dispatches each connection to a different backend Service based on the client’s SNI, using TLSRoute. Because the routes all attach to the same listener, this pattern is not bounded by the per-Gateway listener limit.
TLS Certificates
Create a wildcard certificate that covers every hostname the routes will serve:
The quickstart already deployed a backend Service. Add a second instance of the same echo application so the two TLSRoutes resolve to distinct pods and the SNI routing can be observed end-to-end:
The listener certificate must cover every hostname the attached routes serve — either as a wildcard (as above) or via the cert’s SAN list. Route hostnames must also match the listener’s hostname pattern, otherwise the route will be rejected with a status condition.
Testing
Get the Gateway address using either the LoadBalancer or port-forward variant shown in the TCPRoute Testing section above, then probe each backend by SNI:
The echo response includes the serving pod’s name (POD_NAME), so each request lands on a different backend Service even though they share one listener.
SDS Certificate References
Besides inline kubernetes.io/tls Secrets, a listener’s tls.certificateRefs can reference a Secret of type gateway.envoyproxy.io/sds. Rather than embedding a certificate and key directly, this Secret tells Envoy to fetch the certificate at runtime from an external Secret Discovery Service (SDS) server, identified by two keys: url (the scheme-qualified SDS server Unix domain socket URL) and secretName (the resource name Envoy requests from that server):
This feature is disabled by default. Add enableSDSSecretRef under extensionApis in the EnvoyGateway configuration stored in the envoy-gateway-config ConfigMap:
The SDS Unix domain socket must also be mounted into the Envoy Proxy pod at the path specified by url. For example, the following EnvoyProxy mounts a socket directory provided on every Kubernetes node:
Replace the hostPath with the directory used by the SDS provider. The directory must exist on every node that can run an Envoy Proxy pod. The Envoy process must have permission to connect to the socket. If the GatewayClass already references an EnvoyProxy, add the volume and mount to that resource instead of replacing parametersRef. Enabling SDS Secret references does not add the socket or change the proxy deployment automatically.
Kubernetes authorization and ReferenceGrant control access to the Secret containing the SDS connection details. The SDS server separately authorizes the secretName requested by Envoy using the proxy’s SDS identity. Only enable SDS Secret references when users who can create or reference these Secrets are trusted to request the SDS resources available to that identity. Use separate Envoy Proxy deployments or SDS identities for mutually untrusted tenants.
Envoy waits for SDS-backed listener certificates before activating the listener. Envoy Gateway combines HTTPS listeners on the same address and port into one Envoy listener, so an unavailable SDS server or resource can delay activation or reset connections for every listener sharing that address and port.
To prevent HTTP/2 connection coalescing across HTTPS listeners that share a port, Envoy Gateway normally compares certificate DNS/SAN names and defaults listeners with overlapping certificates to HTTP/1.1 unless ALPN is explicitly configured. Because SDS-backed certificates are opaque to Envoy Gateway, an SDS-backed listener defaults to HTTP/1.1 when multiple valid HTTPS listeners share its port. A same-port listener using an inline TLS Secret also defaults to HTTP/1.1 when one of its known certificate DNS/SAN names overlaps the SDS listener’s configured hostname. If the SDS listener omits hostname and therefore matches all hostnames, every valid same-port HTTPS listener defaults to HTTP/1.1. A standalone SDS-backed listener retains HTTP/2.
Affected listeners report the Envoy Gateway condition gateway.envoyproxy.io/TLSCertificateNamesUnknown=True with reason SDSCertificateOpaque. Configure ALPN explicitly with ClientTrafficPolicy to override the default.
Connecting to an External SDS Server
The url above points at a Unix domain socket served by a process running alongside Envoy in the same pod. To fetch secrets from an SDS server reachable over the network instead, set url to http://<host>:<port> or https://<host>:<port>. Envoy Gateway builds and owns the Envoy cluster for this address itself, the same way it does for the Unix domain socket case:
An http URL never secures the connection to the SDS server: any tlsSettings supplied alongside it is ignored.
To secure the connection with TLS, use an https URL and add a tlsSettings field containing a JSON object with filesystem paths to the client certificate, private key, and CA certificate Envoy uses to authenticate the connection:
An https URL without a tlsSettings field falls back to a plaintext connection, the same as http, and Envoy Gateway logs an error noting the downgrade.
These are paths to raw certificate/key files mounted into the Envoy Proxy pod, not the certificate bytes themselves: mount them the same way the socket directory is mounted for a Unix domain socket SDS server (an EnvoyProxy pod patch), or any other certificate file. This material can’t be sourced from SDS itself, since that would make establishing the SDS connection depend on the SDS connection.
Envoy requires this material in the shape of a locally mounted SDS resource file (read via PathConfigSource), not as raw PEM. Envoy Gateway generates that descriptor file itself from the raw paths above and mounts it alongside the proxy’s other SDS resources, under the same /sds ConfigMap volume Envoy already has for its own xDS bootstrap certificate — no separate action is needed to provision the descriptor file itself, only the raw certificatePath/privateKeyPath/caCertificatePath files. Envoy picks up rotations of those raw files by watching the descriptor’s file path for moves.
This descriptor generation is implemented for the Kubernetes infra provider only. The host and remote infra providers don’t generate it in this release.
Envoy also verifies the SDS server’s certificate hostname: it sends the address’s hostname as the TLS ClientHello SNI and checks it against the certificate’s DNS SAN. If url uses an IP address instead of a hostname, or the certificate’s SAN doesn’t match the address, add sni to tlsSettings to set the hostname explicitly:
A CA certificate and a client certificate can share the same external SDS server: create separate Secrets with the same http(s):// URL but different secretName values, one referenced from caCertificateRefs and the other from clientCertificateRef. processSDSClusters deduplicates by URL, so Envoy Gateway resolves both references against the single cluster.
2.3.23 - Using cert-manager For TLS Termination
This task shows how to set up cert-manager to automatically create certificates and secrets for use by Envoy Gateway.
It will first show how to enable the self-sign issuer, which is useful to test that cert-manager and Envoy Gateway can talk to each other.
Then it shows how to use Let’s Encrypt’s staging environment.
Changing to the Let’s Encrypt production environment is straight-forward after that.
Prerequisites
A Kubernetes cluster and a configured kubectl.
The helm command.
The curl command or similar for testing HTTPS requests.
For the ACME HTTP-01 challenge to work
your Gateway must be reachable on the public Internet.
the domain name you use (we use www.example.com) must point to the Gateway’s external IP(s).
Installation
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
Installing cert-manager is straight-forward and you can follow the below approach to install cert-manager in your cluster. Gateway API CRDs should either be installed before cert-manager starts or the cert-manager Deployment should be restarted after installing the Gateway API CRDs. Remember to enable the Gateway API support. You can refer this page for more details.
You should now have cert-manager running with nothing to do:
$ kubectl wait --for=condition=Available deployment -n cert-manager --all
deployment.apps/cert-manager condition met
deployment.apps/cert-manager-cainjector condition met
deployment.apps/cert-manager-webhook condition met
$ kubectl get -n cert-manager deployment
NAME READY UP-TO-DATE AVAILABLE AGE
cert-manager 1/1 1 1 42m
cert-manager-cainjector 1/1 1 1 42m
cert-manager-webhook 1/1 1 1 42m
A Self-Signing Issuer
cert-manager can have any number of issuer configurations.
The simplest issuer type is SelfSigned.
It simply takes the certificate request and signs it with the private key it generates for the TLS Secret.
Self-signed certificates don't provide any help in establishing trust between certificates.
However, they are great for initial testing, due to their simplicity.
You could instead create a new Gateway serving HTTPS, if you’d prefer.
cert-manager doesn’t care, but we’ll keep it all together in this task.
Nowadays, X.509 certificates don’t use the subject Common Name for hostname matching, so you can set it to whatever you want, or leave it empty.
The important parts here are
the annotation referencing the “selfsigned” ClusterIssuer we created above,
the hostname, which is required (but see #6051 for computing it based on attached HTTPRoutes), and
the named Secret, which is what cert-manager will create for us.
In the interaction between the two, cert-manager does all the heavy lifting.
It subscribes to changes to Gateway resources (using the gateway-shim component.)
For any Gateway it finds, it looks for any TLS listeners, and the associated tls.certificateRefs.
Note that while Gateway API supports multiple refs here, Envoy Gateway only uses one.
cert-manager also looks at the hostname of the listener to figure out which hosts the certificate is expected to cover.
More than one listener can use the same certificate Secret, which means cert-manager needs to find all listeners using the same Secret before deciding what to do.
If the certificatRef points to a valid certificate, given the hostnames found in listeners, cert-manager has nothing to do.
If there is no valid certificate, or it is about to expire, cert-manager’s gateway-shim creates a Certificate resource, or updates the existing one.
cert-manager then follows the Certificate Lifecycle.
To know how to issue the certificate, an ClusterIssuer is configured, and referenced through annotations on the Gateway resource, which you did above.
Once a matching ClusterIssuer is found, that plugin does what needs to be done to acquire a signed certificate.
In the case of the ACME protocol (used by Let’s Encrypt), cert-manager can also use an HTTP Gateway to solve the HTTP-01 challenge type.
This is the other side of cert-manager’s Gateway API support:
the ACME issuer creates a temporary HTTPRoute, lets the ACME server(s) query it, and deletes it again.
cert-manager then updates the Secret that the Gateway’s listener points to in tls.certificateRefs.
Envoy Gateway picks up that the Secret has changed, and reloads the corresponding Envoy Proxy Deployments with the new private key and certificate.
As you can imagine, cert-manager requires quite broad permissions to update Secrets in any namespace, so the security-minded reader may want to look at the RBAC resources the Helm chart creates.
Using the ACME Issuer With Let’s Encrypt and HTTP-01
We will start using the Let’s Encrypt staging environment, to spare their production environment.
Our Gateway already contains an HTTP listener, so we will use that for the HTTP-01 challenges.
You probably want to set the cert-manager.io/revision-history-limit annotation on your Gateway to make cert-manager prune the CertificateRequest history.
cert-manager deletes unused Certificate resources, and they are updated in-place when possible, so there should be no need for cleaning up Certificate resources.
The deletion is based on whether a Gateway still holds a tls.certificateRefs that requires the Certificate.
If you remove a TLS listener from a Gateway, you may still have a Secret lingering.
cert-manager can clean it up using a flag.
Issuer Namespaces
We have used ClusterIssuer resources in this tutorial.
They are not bound to any namespace, and will read annotations from Gateways in any namespace.
You could also use Issuer, which is bound to a namespace.
This is useful e.g. if you want to use different ACME accounts for different namespaces.
If you change the issuer kind, you also need to change the annotation key from cert-manager.io/clusterissuer to cert-manager.io/issuer.
Using ExternalDNS
The ExternalDNS controller maintains DNS records based on Kubernetes resources.
Together with cert-manager, this can be used to fully automate hostname management.
It can use various source resources, among them Gateway Routes.
Just specify a Gateway Route resource, let ExternalDNS create the domain records, and then cert-manager the TLS certificate.
The tutorial on Gateway API uses kubectl.
They also have a Helm chart, which is easier to customize.
The only thing relevant to Envoy Gateway is to set the sources:
The Issuer has a Ready condition (though this is rather boring for the selfSigned type):
$ kubectl get issuer --all-namespaces
NAMESPACE NAME READY AGE
default selfsigned True 42m
The Gateway will say when it has an invalid certificate:
$ kubectl describe gateway/eg
...
Conditions:
Message: Secret default/eg-https does not exist.
Reason: InvalidCertificateRef
Status: False
Type: ResolvedRefs
...
Message: Listener is invalid, see other Conditions for details.
Reason: Invalid
Status: False
Type: Programmed
...
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Warning BadConfig 42m cert-manager-gateway-shim Skipped a listener block: spec.listeners[1].hostname: Required value: the hostname cannot be empty
The main question is if cert-manager has picked up on the Gateway.
I.e., has it created a Certificate for it?
The above describe contains an event from cert-manager-gateway-shim telling you of one such issue.
Be aware that if you have a non-TLS listener in the Gateway, like we did, there will be events saying it is not eligible, which is of course expected.
Another option is looking at Deployment logs.
The cert-manager logs are not very verbose by default, but setting the Helm value global.logLevel to 6 will enable all debug logs (the default is 2.)
This will make them verbose enough to say why a Gateway wasn’t considered (e.g. missing hostname, or tls.mode is not Terminate.)
Simply listing Certificate resources may be useful, even if it just gives a yes/no answer:
$ kubectl get certificate --all-namespaces
NAMESPACE NAME READY SECRET AGE
default eg-https True eg-https 42m
If there is a Certificate, then the gateway-shim has recognized the Gateway.
But is there a CertificateRequest for it?
(BTW, don’t confuse this with a CertificateSigningRequest, which is a Kubernetes core resource type representing the same thing.)
$ kubectl get certificaterequest --all-namespaces
NAMESPACE NAME APPROVED DENIED READY ISSUER REQUESTOR AGE
default eg-https-xxxxx True True selfsigned system:serviceaccount:cert-manager:cert-manager 42m
The ACME issuer also has Order and Challenge resources to watch:
$ kubectl get order --all-namespaces -o wide
NAME STATE ISSUER REASON AGE
order.acme.cert-manager.io/envoy-https-xxxxx-123456789 pending letsencrypt-staging 42m
$ kubectl get challenge --all-namespaces
NAME STATE DOMAIN AGE
challenge.acme.cert-manager.io/envoy-https-xxxxx-123456789-1234567890 pending www.example.com 42m
Using kubetctl get -o wide or kubectl describe on the Challenge will explain its state more.
$ kubectl get order --all-namespaces -o wide
NAME STATE ISSUER REASON AGE
order.acme.cert-manager.io/envoy-https-xxxxx-123456789 valid letsencrypt-staging 42m
Finally, since cert-manager creates the Secret referenced by the Gateway listener as its last step, we can also look for that:
$ kubectl get secret secret/eg-https
NAME TYPE DATA AGE
eg-https kubernetes.io/tls 3 42m
An extension may need to call another service before allowing a request to
continue, for example to check authorization or look up a key. Declare that
service in EnvoyExtensionPolicy.spec.backends so Envoy Gateway can configure
the connection for Lua, Wasm or dynamic module HTTP callouts.
Envoy sends these calls through a cluster, which holds the backend’s endpoints
and connection settings. Your extension uses an alias you choose, such as
resolver, to find the cluster name during a request. This keeps generated
cluster names out of your extension configuration and lets you change the
backend reference while keeping the same alias in your code. Envoy Gateway
resolves endpoints, authorizes references and configures backend TLS.
Enable extension backends
Extension backend bindings are disabled by default. To enable them, set
extensionApis.enableExtensionBackends: true in the EnvoyGateway configuration:
This setting applies to Service, ServiceImport and Backend references for all
supported extension runtimes. References to Backend resources additionally require
extensionApis.enableBackend: true. For the Lua example, also
enable Lua support.
While extension backends are disabled, policies that declare or inherit bindings
are rejected with Accepted=False, and affected routes return HTTP 500. Policies
without bindings continue to work.
Declare a backend
In spec.backends, name defines the alias your extension uses. The
backendRef.name identifies a Kubernetes resource by its metadata.name. That
resource can be a Service, ServiceImport or Envoy Gateway Backend. A
Backend resource defines destinations such as IP
addresses, DNS names and Unix socket paths. The alias and resource name can differ.
This policy binds the alias resolver to the Kubernetes Service lookup-service.
The Lua script looks up that alias and calls the resulting cluster. The Service does not need
to appear in the HTTPRoute’s backendRefs. Your route can send client requests
to the application while the extension uses a separate service for its lookup.
apiVersion:gateway.envoyproxy.io/v1alpha1kind:EnvoyExtensionPolicymetadata:name:resolverpolicynamespace:defaultspec:targetRefs:- group:gateway.networking.k8s.iokind:HTTPRoutename:appbackends:- name:resolverbackendRef:name:lookup-serviceport:8080lua:- type:Inlineinline:| function envoy_on_request(handle)
local cluster = handle:route():metadata():get("resolver")
if cluster == nil then
handle:respond({[":status"] = "502"}, "missing resolver binding")
return
end
local headers = handle:httpCall(cluster, {
[":method"] = "GET",
[":path"] = "/lookup",
[":authority"] = "lookup-service"
}, nil, 2000)
if headers[":status"] ~= "200" then
handle:respond({[":status"] = "502"}, "resolver callout failed")
end
end
If the lookup returns HTTP 200, the original request continues to the route’s
backend. Otherwise, the script responds with HTTP 502.
Aliases must be lowercase DNS labels and unique within the policy, with at most
16 bindings. resolver is an example alias chosen by the operator. Separate
policies can use the same alias for different Services on the same proxy. Lua,
Wasm and dynamic modules using the same effective policy share its backend bindings.
The HTTP authority, path, timeout and response handling remain part of extension
configuration or code. The alias supplies only the Envoy cluster name.
Configure backend connections
Use backendSettings to control how Envoy connects to the callout service.
For example, this binding allows three seconds to establish a connection and
limits the cluster to 100 connections:
These settings configure the callout cluster. Omitted settings use existing
defaults. Inherited bindings keep their settings. BackendTrafficPolicy settings
for route traffic do not apply to these callouts. A connection timeout limits
how long Envoy waits to connect. The extension controls how long it waits for
an individual callout and whether to retry. For that reason, requestTimeout
and streamIdleTimeout are rejected here. DynamicModule load balancing and
HTTP/3 are not supported for extension backends.
Backend references support the same resources as external processing services:
Service, ServiceImport and Envoy Gateway Backend. Enable the Backend API before
referencing Backend resources. References to another namespace require a ReferenceGrant
allowing gateway.envoyproxy.io/EnvoyExtensionPolicy from the declaring policy’s
namespace. BackendTLSPolicy and applicable backend TLS settings are resolved by
Envoy Gateway.
DynamicResolver backends and mixed DNS/static endpoint sets are not supported.
Use a Unix socket backend
Reference a Backend resource to reach a sidecar over a Unix socket:
Enable the Backend API and mount the socket directory in both Envoy and the
sidecar. Operators manage the sidecar and socket lifecycle. Extensions use the
same alias lookup and HTTP callout APIs as for a Service.
Read a binding
The alias map is stored in Envoy’s route metadata with the route
configuration. Reading it is a local lookup, with no request to Envoy Gateway
or Kubernetes. It is not an HTTP header and is not sent to the backend service.
Envoy Gateway publishes a flat map of aliases to cluster names in
the selected route’s metadata.filter_metadata under
gateway.envoyproxy.io/extension-backends. It also publishes the map under each
Lua filter’s exact name, because Lua’s metadata accessor selects that namespace.
Lua uses handle:route():metadata():get("resolver"), as above.
A Wasm extension uses its SDK’s property getter with this path:
Decode the returned bytes as a UTF-8 cluster name and pass it to
dispatch_http_call (or the equivalent call in the SDK).
The dynamic module Go SDK provides this lookup:
cluster,found:=handle.GetMetadataString(shared.MetadataSourceTypeRoute,"gateway.envoyproxy.io/extension-backends","resolver",)if!found{// Return a local error for the missing binding.return}// Use cluster.ToString() as the cluster argument to handle.HttpCallout.
The Rust SDK provides get_metadata_string with metadata source Route and the
same namespace and key. SDK buffers can borrow Envoy memory. Copy the string if
it must outlive the callback. See the dynamic module test example for a complete
HTTP callout using the Go SDK.
Security considerations
Backend bindings allow policy authors to configure outbound traffic from Envoy.
ReferenceGrant checks authorize references to Kubernetes resources, but they
do not prevent SSRF or restrict the network destinations behind those resources.
Aliases identify clusters, however they do not restrict which clusters a dynamic
module can call. Use trusted modules and restrict who can configure policies and
referenced backends.
A child policy can use inherited bindings or replace them while retaining the
parent’s extension. Replacing an authorization backend could therefore change
authorization decisions.
Active health checks can also generate traffic without extension calls. Use
admission controls and network restrictions when delegating policy management.
Scope and lifecycle
Bindings belong to the selected route, so a shared extension can call different
services for different applications. Always resolve the alias for the current
request rather than keeping one cluster name for the lifetime of the extension.
Look up bindings while processing request headers or later in the request’s
context. Initialization and independent background tasks have no request route.
Asynchronous callout completion remains supported. Resolve the binding in request
context and use it only for that request, copying borrowed strings if needed.
Do not cache a binding across requests: another route can map the same
alias to a different backend, including when the same filter instance serves both
routes. Handle missing bindings explicitly and treat generated cluster names as
opaque. Route changes can change which bindings are available.
Normal EnvoyExtensionPolicy attachment precedence applies. When merging a route
policy with a parent policy, an omitted or empty backends list inherits the parent’s
bindings and reference namespace. A supplied nonempty list replaces the whole
list, so repeat every binding needed by inherited extensions. This also lets a
route intentionally rebind an alias used by an inherited extension. Without
merging, only the selected policy’s bindings apply.
For example, a Gateway policy can provide a common lookup service. A route
policy that merges with it can replace the resolver binding to use a service
for that application while retaining the parent’s extension code.
Invalid references set the policy’s Accepted condition to False and affected
routes return HTTP 500 until the dependency is corrected. This applies even when
a Wasm extension has failOpen enabled: the policy’s declared dependency is
invalid. Unrelated policies continue to operate.
2.4.2 - Build a Wasm image
Envoy Gateway supports two types of Wasm extensions within the EnvoyExtensionPolicy API: HTTP Wasm Extensions and Image Wasm Extensions.
Packaging a Wasm extension as an OCI image is beneficial because it simplifies versioning and distribution for users.
Additionally, users can leverage existing image toolchain to build and manage Wasm images.
This document describes how to build OCI images which are consumable by Envoy Gateway.
Wasm Image Formats
There are two types of images that are supported by Envoy Gateway. One is in the Docker format, and another is the standard
OCI specification compliant format. Please note that both of them are supported by any OCI registries. You can choose
either format depending on your preference, and both types of images are consumable by Envoy Gateway EnvoyExtensionPolicy API.
Build Wasm Docker image
We assume that you have a valid Wasm binary named plugin.wasm. Then you can build a Wasm Docker image with the Docker CLI.
First, we prepare the following Dockerfile:
$ cat Dockerfile
FROM scratch
COPY plugin.wasm ./
Note: you must have exactly one COPY instruction in the Dockerfile in order to end up having only one layer in produced images.
Then, build your image via docker build command
$ docker build . -t my-registry/mywasm:0.1.0
Finally, push the image to your registry via docker push command
$ docker push my-registry/mywasm:0.1.0
Build Wasm OCI image
We assume that you have a valid Wasm binary named plugin.wasm, and you have buildah installed on your machine.
Then you can build a Wasm OCI image with the buildah CLI.
First, we create a working container from scratch base image with buildah from command.
$ buildah --name mywasm from scratch
mywasm
Then copy the Wasm binary into that base image by buildah copy command to create the layer.
This task provides instructions for configuring Dynamic Modules.
Dynamic Modules are a critical extension mechanism that allows functionality to be loaded directly into the Envoy proxy process at runtime, typically as shared object files (.so). This approach enables customized filtering and request processing without requiring a full recompile of the core Envoy binary, streamlining deployments and upgrades.
Envoy Gateway is able to load dynamic modules from the local filesystem using EnvoyExtensionPolicy. This example demonstrates it’s working by loading the Coraza Web Application Firewall (WAF) using Built On Envoy development toolkit. The module’s full documentation can be found on the Coraza WAF extension page.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The entire configuration can also be specified directly on the Gateway instead by using spec.envoyProxy.
Configuration
Create a new EnvoyExtensionPolicy resource to configure the dynamic module for an entire Gateway or per HTTPRoute.
This EnvoyExtensionPolicy targets the Gateway “eg” created with the quickstart. It loads the Coraza WAF extension with its configuration.
cat <<EOF | kubectl apply -f -
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyExtensionPolicy
metadata:
name: waf-extension
spec:
targetRefs:
- group: gateway.networking.k8s.io
kind: Gateway
name: eg
dynamicModule:
- name: composer
filterName: coraza-waf
config:
directives:
- Include @coraza.conf
- SecRuleEngine On
- SecResponseBodyAccess Off
- Include @crs-setup.conf
- Include @owasp_crs/*.conf
EOF
Save and apply the following resource to your cluster:
---apiVersion:gateway.envoyproxy.io/v1alpha1kind:EnvoyExtensionPolicymetadata:name:waf-extensionspec:targetRefs:- group:gateway.networking.k8s.iokind:Gateway# or e.g. HTTPRoutename:egdynamicModule:- name:composerfilterName:coraza-wafconfig:directives:- Include @coraza.conf- SecRuleEngine On- SecResponseBodyAccess Off- Include @crs-setup.conf- Include @owasp_crs/*.conf
Verify the Envoy Extension Policy configuration:
kubectl get envoyextensionpolicy/waf-extension -o yaml
Testing
Ensure the GATEWAY_HOST environment variable from the Quickstart is set. If not, follow the
Quickstart instructions to set the variable.
This task explains the usage of the EnvoyPatchPolicy API.
Note: This API is meant for users extremely familiar with Envoy xDS semantics.
Also before considering this API for production use cases, please be aware that this API
is unstable and the outcome may change across versions. Use at your own risk.
Introduction
The EnvoyPatchPolicy API allows user to modify the output xDS
configuration generated by Envoy Gateway intended for EnvoyProxy,
using JSON Patch semantics.
Motivation
This API was introduced to allow advanced users to be able to leverage Envoy Proxy functionality
not exposed by Envoy Gateway APIs today.
Security Warning
Security Warning
Enabling EnvoyPatchPolicy may lead to complete security compromise of your system.
Users with EnvoyPatchPolicy permissions can inject arbitrary configuration to proxies,
leading to high Confidentiality, Integrity and Availability risks.
Injected configuration may include arbitrary code executed by the proxy without any isolation. Such code may be used
to launch SSRF attacks, as well as allow users to gain access to proxy credentials as described in CVE-2026-22771.
With such access, users can fetch the complete proxy configuration, including secrets and cluster network topology.
When enabling EnvoyPatchPolicy, additional security measures should be taken by admins to reduce security risks, including:
Using K8s RBAC to restrict access to EnvoyPatchPolicy.
Disabling envoy extensions which are not needed with envoy command line options.
Implementing Kubernetes network policies that restrict traffic from the proxy pod only to relevant targets.
Use admission control tools to validate EnvoyPatchPolicy resources, ensuring that only approved patches admitted.
Audit EnvoyPatchPolciy resources periodically, and audit logEnvoyPatchPolicy API server operations.
Quickstart
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The default installation of Envoy Gateway installs a default EnvoyGateway configuration and attaches it
using a ConfigMap. In the next step, we will update this resource to enable EnvoyPatchPolicy.
After updating the ConfigMap, you will need to wait the configuration kicks in. You can force the configuration to be reloaded by restarting the envoy-gateway deployment.
Starting from v1.5, Envoy Gateway uses version 2 of the xDS name scheme when generating xDS resources.
Because EnvoyPatchPolicy relies on specific xDS resource names, it’s important to use the correct naming format when authoring a patch policy.
Use EnvoyProxy’s Local Reply Modification feature to return a custom response back to the client when
the status code is 404
Apply the configuration
cat <<EOF | kubectl apply -f -
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyPatchPolicy
metadata:
name: custom-response-patch-policy
namespace: default
spec:
targetRef:
group: gateway.networking.k8s.io
kind: Gateway
name: eg
type: JSONPatch
jsonPatches:
- type: "type.googleapis.com/envoy.config.listener.v3.Listener"
# The listener name is of the form <GatewayNamespace>/<GatewayName>/<GatewayListenerName>
name: default/eg/http
operation:
op: add
path: "/default_filter_chain/filters/0/typed_config/local_reply_config"
value:
mappers:
- filter:
status_code_filter:
comparison:
op: EQ
value:
default_value: 404
runtime_key: key_b
status_code: 406
body:
inline_string: "could not find what you are looking for"
EOF
Save and apply the following resource to your cluster:
---apiVersion:gateway.envoyproxy.io/v1alpha1kind:EnvoyPatchPolicymetadata:name:custom-response-patch-policynamespace:defaultspec:targetRef:group:gateway.networking.k8s.iokind:Gatewayname:egtype:JSONPatchjsonPatches:- type:"type.googleapis.com/envoy.config.listener.v3.Listener"# The listener name is of the form <GatewayNamespace>/<GatewayName>/<GatewayListenerName>name:default/eg/httpoperation:op:addpath:"/default_filter_chain/filters/0/typed_config/local_reply_config"value:mappers:- filter:status_code_filter:comparison:op:EQvalue:default_value:404runtime_key:key_bstatus_code:406body:inline_string:"could not find what you are looking for"
When mergeGateways is enabled, there will be one Envoy deployment for all Gateways in the cluster.
Then the EnvoyPatchPolicy should target a specific GatewayClass.
cat <<EOF | kubectl apply -f -
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyPatchPolicy
metadata:
name: custom-response-patch-policy
namespace: default
spec:
targetRef:
group: gateway.networking.k8s.io
kind: GatewayClass
name: eg
type: JSONPatch
jsonPatches:
- type: "type.googleapis.com/envoy.config.listener.v3.Listener"
# The listener name is of the form <GatewayNamespace>/<GatewayName>/<GatewayListenerName>
name: default/eg/http
operation:
op: add
path: "/default_filter_chain/filters/0/typed_config/local_reply_config"
value:
mappers:
- filter:
status_code_filter:
comparison:
op: EQ
value:
default_value: 404
runtime_key: key_b
status_code: 406
body:
inline_string: "could not find what you are looking for"
EOF
Save and apply the following resource to your cluster:
---apiVersion:gateway.envoyproxy.io/v1alpha1kind:EnvoyPatchPolicymetadata:name:custom-response-patch-policynamespace:defaultspec:targetRef:group:gateway.networking.k8s.iokind:GatewayClassname:egtype:JSONPatchjsonPatches:- type:"type.googleapis.com/envoy.config.listener.v3.Listener"# The listener name is of the form <GatewayNamespace>/<GatewayName>/<GatewayListenerName>name:default/eg/httpoperation:op:addpath:"/default_filter_chain/filters/0/typed_config/local_reply_config"value:mappers:- filter:status_code_filter:comparison:op:EQvalue:default_value:404runtime_key:key_bstatus_code:406body:inline_string:"could not find what you are looking for"
Edit the HTTPRoute resource from the Quickstart to only match on paths with value /get
$ curl --header "Host: www.example.com" http://$GATEWAY_HOST/find
Handling connection for8888could not find what you are looking for
Customize VirtualHost by name
Use EnvoyProxy’s include_attempt_count_in_response feature to include the attempt count as header in the downstream response.
Apply the configuration
cat <<EOF | kubectl apply -f -
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyPatchPolicy
metadata:
name: include-attempts
namespace: default
spec:
targetRef:
group: gateway.networking.k8s.io
kind: Gateway
name: eg
type: JSONPatch
jsonPatches:
- type: "type.googleapis.com/envoy.config.route.v3.RouteConfiguration"
# The RouteConfiguration name is of the form <GatewayNamespace>/<GatewayName>/<GatewayListenerName>
name: default/eg/http
operation:
op: add
# Every virtual_host that ends with 'www_example_com' (using RegEx Filter)
jsonPath: "..virtual_hosts[?match(@.name, '.*www_example_com')]"
# If the property does not exists, it can not be selected with jsonPath
# Therefore the new property must be set in path
path: "include_attempt_count_in_response"
value: true
EOF
Save and apply the following resource to your cluster:
---apiVersion:gateway.envoyproxy.io/v1alpha1kind:EnvoyPatchPolicymetadata:name:include-attemptsnamespace:defaultspec:targetRef:group:gateway.networking.k8s.iokind:Gatewayname:egtype:JSONPatchjsonPatches:- type:"type.googleapis.com/envoy.config.route.v3.RouteConfiguration"# The RouteConfiguration name is of the form <GatewayNamespace>/<GatewayName>/<GatewayListenerName>name:default/eg/httpoperation:op:add# Every virtual_host that ends with 'www_example_com' (using RegEx Filter)jsonPath:"..virtual_hosts[?match(@.name, '.*www_example_com')]"# If the property does not exists, it can not be selected with jsonPath# Therefore the new property must be set in pathpath:"include_attempt_count_in_response"value:true
Save and apply the following resource to your cluster:
---apiVersion:gateway.envoyproxy.io/v1alpha1kind:EnvoyPatchPolicymetadata:name:add-external-clusternamespace:defaultspec:targetRef:group:gateway.networking.k8s.iokind:Gatewayname:egtype:JSONPatchjsonPatches:- type:"type.googleapis.com/envoy.config.cluster.v3.Cluster"# Adds a new STRICT_DNS cluster named external-svc-clustername:external-svc-clusteroperation:op:addpath:""value:name:external-svc-clustertype:STRICT_DNSconnect_timeout:10slb_policy:ROUND_ROBINload_assignment:cluster_name:external-svc-clusterendpoints:- lb_endpoints:- endpoint:address:socket_address:address:example.external.svcport_value:8443
Modify load balancing on an HTTPRoute cluster
Use EnvoyPatchPolicy to modify an upstream cluster generated for an HTTPRoute rule.
This example replaces the default load balancing policy with client-side weighted round robin.
Cluster names follow the format httproute/<HTTPRouteNamespace>/<HTTPRouteName>/rule/<RuleIndex>.
For the backend HTTPRoute from the Quickstart prerequisites in namespace default, the cluster name is
httproute/default/backend/rule/0.
Use egctl x translate to confirm the exact cluster name in your environment before applying a patch.
Envoy Gateway already sets load_balancing_policy on generated clusters, so use replace instead of add
when modifying that field.
Save and apply the following resource to your cluster:
---apiVersion:gateway.envoyproxy.io/v1alpha1kind:EnvoyPatchPolicymetadata:name:backend-client-wrrnamespace:defaultspec:type:JSONPatchtargetRef:group:gateway.networking.k8s.iokind:Gatewayname:egjsonPatches:- type:type.googleapis.com/envoy.config.cluster.v3.Cluster# Cluster name for HTTPRoute rule 0 in namespace defaultname:httproute/default/backend/rule/0operation:op:replacepath:/load_balancing_policyvalue:policies:- typed_extension_config:name:envoy.load_balancing_policies.client_side_weighted_round_robintyped_config:"@type": type.googleapis.com/envoy.extensions.load_balancing_policies.client_side_weighted_round_robin.v3.ClientSideWeightedRoundRobin
Verify the patch was applied by checking the EnvoyPatchPolicy status
kubectl get envoypatchpolicy backend-client-wrr -n default -o yaml
The Programmed=True condition confirms the patch was applied. You can also inspect the generated
cluster configuration with egctl x translate:
Bind backend connections to a specific source address
cat <<EOF | kubectl apply -f -
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyPatchPolicy
metadata:
name: cluster-source-bind
namespace: default
spec:
targetRef:
group: gateway.networking.k8s.io
kind: Gateway
name: eg
type: JSONPatch
jsonPatches:
- type: "type.googleapis.com/envoy.config.cluster.v3.Cluster"
# For clusters generated from HTTPRoute, the default name is:
# httproute/<NAMESPACE>/<NAME>/rule/<RULE_NUMBER>
# e.g. httproute/default/backend/rule/0
name: httproute/default/backend/rule/0
operation:
op: add
path: "/upstream_bind_config"
value:
source_address:
address: 10.0.0.5
port_value: 0
EOF
Save and apply the following resource to your cluster:
---apiVersion:gateway.envoyproxy.io/v1alpha1kind:EnvoyPatchPolicymetadata:name:cluster-source-bindnamespace:defaultspec:targetRef:group:gateway.networking.k8s.iokind:Gatewayname:egtype:JSONPatchjsonPatches:- type:"type.googleapis.com/envoy.config.cluster.v3.Cluster"# For clusters generated from HTTPRoute, the default name is:# httproute/<NAMESPACE>/<NAME>/rule/<RULE_NUMBER># e.g. httproute/default/backend/rule/0name:httproute/default/backend/rule/0operation:op:addpath:"/upstream_bind_config"value:source_address:address:10.0.0.5port_value:0
Debugging
Runtime
The Status subresource should have information about the status of the resource. Make sure
Accepted=True and Programmed=True conditions are set to ensure that the policy has been
applied to Envoy Proxy.
apiVersion:gateway.envoyproxy.io/v1alpha1kind:EnvoyPatchPolicymetadata:annotations:kubectl.kubernetes.io/last-applied-configuration:| {"apiVersion":"gateway.envoyproxy.io/v1alpha1","kind":"EnvoyPatchPolicy","metadata":{"annotations":{},"name":"custom-response-patch-policy","namespace":"default"},"spec":{"jsonPatches":[{"name":"default/eg/http","operation":{"op":"add","path":"/default_filter_chain/filters/0/typed_config/local_reply_config","value":{"mappers":[{"body":{"inline_string":"could not find what you are looking for"},"filter":{"status_code_filter":{"comparison":{"op":"EQ","value":{"default_value":404}}}}}]}},"type":"type.googleapis.com/envoy.config.listener.v3.Listener"}],"priority":0,"targetRef":{"group":"gateway.networking.k8s.io","kind":"Gateway","name":"eg","namespace":"default"},"type":"JSONPatch"}}creationTimestamp:"2023-07-31T21:47:53Z"generation:1name:custom-response-patch-policynamespace:defaultresourceVersion:"10265"uid:a35bda6e-a0cc-46d7-a63a-cee765174bc3spec:jsonPatches:- name:default/eg/httpoperation:op:addpath:/default_filter_chain/filters/0/typed_config/local_reply_configvalue:mappers:- body:inline_string:could not find what you are looking forfilter:status_code_filter:comparison:op:EQvalue:default_value:404type:type.googleapis.com/envoy.config.listener.v3.Listenerpriority:0targetRef:group:gateway.networking.k8s.iokind:Gatewayname:egtype:JSONPatchstatus:conditions:- lastTransitionTime:"2023-07-31T21:48:19Z"message:EnvoyPatchPolicy has been accepted.observedGeneration:1reason:Acceptedstatus:"True"type:Accepted- lastTransitionTime:"2023-07-31T21:48:19Z"message:successfully applied patches.reason:Programmedstatus:"True"type:Programmed
Offline
You can use egctl x translate to validate the translated xds output.
Caveats
This API will always be an unstable API and the same outcome cannot be guaranteed
across versions for these reasons
The Envoy Proxy API might deprecate and remove API fields
Envoy Gateway might alter the xDS translation creating a different xDS output
such as changing the name field of resources.
2.4.5 - Envoy Gateway Extension Server
This task explains how to extend Envoy Gateway using an Extension Server. Envoy Gateway
can be configured to call an external server over gRPC with the xDS configuration before
it is sent to Envoy Proxy. The external server can modify the provided configuration
programmatically using any semantics supported by the xDS API.
Using an extension server allows vendors to add xDS configuration that Envoy Gateway itself
doesn’t support with a very high level of control over the generated xDS configuration.
Note: Modifying the xDS configuration generated by Envoy Gateway may break functionality
configured by native Envoy Gateway means. Like other cases where the xDS configuration
is modified outside of Envoy Gateway’s control, this is risky and should be tested thoroughly,
especially when using the same extension server across different Envoy Gateway versions.
Introduction
One of the Envoy Gateway project goals is to “provide a common foundation for vendors to
build value-added products without having to re-engineer fundamental interactions”. The
Envoy Gateway Extension Server provides a mechanism where Envoy Gateway tracks all provider
resources and then calls a set of hooks that allow the generated xDS configuration to be
modified before it is sent to Envoy Proxy. See the design documentation for full details.
Security Warning
Security Warning
Enabling an Extension Server may lead to complete security compromise of your system.
Users that control the Extension Server can inject arbitrary configuration to proxies,
leading to high Confidentiality, Integrity and Availability risks.
Injected configuration may include arbitrary code executed by the proxy without any isolation. Such code may be used
to launch SSRF attacks, as well as allow users to gain access to proxy credentials as described in CVE-2026-22771.
With such access, users can fetch the complete proxy configuration, including secrets and cluster network topology.
When enabling Extension Server, additional security measures should be taken by admins to reduce security risks, including:
Using K8s RBAC to restrict access to the Envoy Gateway Configuration as well as the Extension Server deployment.
Disabling envoy extensions which are not needed with envoy command line options.
Implementing Kubernetes network policies that restrict traffic from the proxy pod only to relevant targets.
Resources registered under secretResources are created by users, who may be less trusted than the
Extension Server. The Secret hook resolves such a resource to a secret that Envoy loads, so the
Extension Server decides which secret a user’s resource gives access to. Envoy Gateway only checks that
the reference is to a registered kind, is permitted by a ReferenceGrant, and exists, and it ignores a
resolution to a secret it provides to Envoy itself (for example, the xDS client certificate). It cannot
check any other secret name or SDS server. The Extension Server must make sure a resource only resolves
to secrets its owner is allowed to use, and must not pass a user-supplied secret name through unchecked.
Extension Hooks Overview
Envoy Gateway provides several extension hooks that are called at different stages of the xDS translation process. These hooks allow extensions to modify various aspects of the generated xDS configuration:
Available Hooks
Hook Type
Hook Method Name
Purpose
Resources Modified
Execution Context
Route
PostRouteModifyHook
Modify individual routes
Single envoy.config.route.v3.Route
Per-route, only for routes with extension filters or extension server policies targeting them
Cluster
PostClusterModifyHook
Modify clusters for custom backends
Single envoy.config.cluster.v3.Cluster
Per-cluster, only for custom backend clusters
VirtualHost
PostVirtualHostModifyHook
Modify virtual hosts and add custom routes
Single envoy.config.route.v3.VirtualHost
Per-virtual-host; receives extension server policies targeting the listener that owns the virtual host
HTTPListener
PostHTTPListenerModifyHook
Modify HTTP listeners
Single envoy.config.listener.v3.Listener
Per-listener
Secret
ResolveSecretHook
Resolve listener certificates that reference a kind registered under secretResources
Single envoy.extensions.transport_sockets.tls.v3.SdsSecretConfig
Per-certificate, only for certificates referencing a registered kind
Translation
PostTranslateModifyHook
Global modification of all xDS resources
All clusters, secrets, listeners, and routes
Once per translation cycle
Hook Execution Order
The hooks are executed in the following order during xDS translation:
Route Processing Phase
Secret hook (ResolveSecretHook): Called for each certificate of a listener that references a kind registered under secretResources, before the listener’s routes are processed
Route hook (PostRouteModifyHook): Called for each route that has extension filters attached or extension server policies targettig the route
Cluster hook (PostClusterModifyHook): Called for each cluster generated from custom backend references
Virtual Host Processing Phase
VirtualHost hook (PostVirtualHostModifyHook): Called for each virtual host after all routes are processed
Listener Processing Phase
HTTPListener hook (PostHTTPListenerModifyHook): Called for each HTTP listener after virtual hosts are configured
Final Translation Phase
Translation hook (PostTranslateModifyHook): Called once with all generated clusters, secrets, listeners, and routes
Hook Details
Route Hook (PostRouteModifyHook)
When called: After each individual route is generated from an HTTPRoute or GRPCRoute that has extension filters attached or has extension server policies targeting it (or one of its rules)
Input: Single route, hostnames, the extension resources from the HTTPRoute or GRPCRoute, and the extension server policies targeting the route or its matching rule
When called: Once for each custom backendRef with a non-zero weight. Each custom backendRef gets its own
cluster. Clusters for Service, ServiceImport or Backend backendRefs in the same rule don’t call the hook.
Input: Single cluster, and in PostClusterContext.backend_extension_resources the custom backend resource
for that cluster, plus any resources from the route’s extensionRef filters
Output: Modified cluster
Use cases: Configure custom backend clusters, add health checks, modify load balancing
Use cases: Add virtual host-level configuration, inject additional routes
HTTPListener Hook (PostHTTPListenerModifyHook)
When called: After listener is fully configured with all virtual hosts
Input: Complete HTTP listener and associated extension policies
Output: Modified listener
Use cases: Add listener filters, modify listener configuration, add authentication
Secret Hook (ResolveSecretHook)
When called: For each listener certificate that references a kind registered under secretResources
Input: The referenced resource (secret_resource), and the name and namespace of the data plane the listener
is translated for (proxy)
Output: How Envoy obtains the secret (sds_secret_config), or a failure reason when it cannot be resolved
yet (failure_reason, failure_message). sds_secret_config must have a name. Its sds_config may be left
unset when the data plane resolves the name itself. A response with neither is treated as unresolved.
Use cases: Serve listener certificates held by an external provider, without storing the key in a Kubernetes Secret
Unresolved certificates: A certificate that is not resolved is left out of the listener. If none of a
listener’s certificates are resolved, Envoy closes the connections for the listener’s hostnames, rather than
letting another listener on the same port, such as one with a wildcard hostname, handle them. HTTP/3 traffic
for the listener is not served.
Errors: A hook error fails translation even when failOpen is set, so Envoy keeps its last good
configuration. Report a certificate that cannot be served yet with a failure reason, not an error.
Translation Hook (PostTranslateModifyHook)
When called: After all individual resources are generated and processed
Input: All clusters, secrets, listeners, and routes, plus extension policies targeting Gateways (or, with
mergeGateways enabled, the GatewayClass)
Output: Complete set of modified resources
Use cases: Global resource injection, cross-resource modifications, cleanup operations
Targeting Resources with Extension Server Policies
Extension server policies (the custom resources registered via extensionManager.policyResources) attach to
Envoy Gateway resources through their targetRefs/targetRef (with an optional sectionName) or through
targetSelectors. The target determines which hooks receive the policy:
targetRef kind
sectionName
Attaches to
Delivered to hook(s)
Gateway
(unset)
The whole Gateway
PostVirtualHostModifyHook (once for each listener’s virtual host), PostHTTPListenerModifyHook, PostTranslateModifyHook
Gateway
Listener name
A single Listener
PostVirtualHostModifyHook (virtual host of that listener only), PostHTTPListenerModifyHook, PostTranslateModifyHook
GatewayClass
(unset)
Every listener of every Gateway in the class (requires mergeGateways)
PostVirtualHostModifyHook (once for each listener’s virtual host), PostHTTPListenerModifyHook, PostTranslateModifyHook
ListenerSet
(unset)
Every listener of the ListenerSet
PostVirtualHostModifyHook (once for each listener’s virtual host), PostHTTPListenerModifyHook, PostTranslateModifyHook (of the parent Gateway)
ListenerSet
Listener name
A single Listener of the ListenerSet
PostVirtualHostModifyHook (virtual host of that listener only), PostHTTPListenerModifyHook, PostTranslateModifyHook (of the parent Gateway)
HTTPRoute / GRPCRoute
(unset)
All rules of the route
PostRouteModifyHook (every route generated from the HTTPRoute/GRPCRoute)
HTTPRoute / GRPCRoute
Rule name (sectionName)
A single route rule
PostRouteModifyHook (routes generated from that rule only)
Targeting a GatewayClass
A policy can target a GatewayClass only when mergeGateways is enabled for that class. With
merged Gateways, every Gateway of the class shares one Envoy fleet and one xDS translation, so a class-level policy
has a single, well-defined place to attach:
It is attached to every listener (HTTP, TCP and UDP) of every Gateway in the class, including listeners contributed
by ListenerSets, and is therefore delivered to PostVirtualHostModifyHook (once per listener’s virtual host) and
PostHTTPListenerModifyHook for each of those listeners.
It is delivered once to PostTranslateModifyHook for the merged translation of the class.
sectionName is not supported on a GatewayClass target. To select a single listener, target the Gateway with
sectionName instead.
apiVersion:example.extensions.io/v1alpha1kind:ListenerContextExamplemetadata:name:class-wide-policynamespace:defaultspec:targetRefs:- group:gateway.networking.k8s.iokind:GatewayClassname: eg # a GatewayClass whose EnvoyProxy sets mergeGateways:true
A GatewayClass can also be selected through targetSelectors by matching its labels. Because a GatewayClass is
cluster-scoped, the selector’s namespaces field and ReferenceGrants do not apply to it.
Targeting a ListenerSet
A policy can target a ListenerSet, or a single listener of it through sectionName. The policy is
attached only to the ListenerSet’s own listeners, and status is reported against the ListenerSet rather than its
parent Gateway. A Gateway target without sectionName already covers the listeners contributed by its
ListenerSets, while a Gateway target with sectionName only matches the Gateway’s own listeners.
apiVersion:example.extensions.io/v1alpha1kind:ListenerContextExamplemetadata:name:listenerset-policynamespace:defaultspec:targetRefs:- group:gateway.networking.k8s.iokind:ListenerSetname:team-a-listenerssectionName:https # optional, selects a single listener of the ListenerSet
Important: Policies targeting a GatewayClass, a Gateway, a ListenerSet, and policies targeting an HTTPRoute or GRPCRoute are evaluated independently. Envoy Gateway does not merge, override, or resolve conflicts between them. For example, a policy attached to an HTTPRoute does not override a policy of the same kind attached to its Gateway. Any merging, overriding, or conflict resolution behavior must be implemented by the Extension Server.
Cross-namespace attachment
Direct targetRefs / targetRef to a namespaced target (Gateway, ListenerSet, HTTPRoute, GRPCRoute) are always resolved
in the policy’s own namespace, they cannot reference a target in another namespace. A GatewayClass is
cluster-scoped, so a policy in any namespace can target it directly without a ReferenceGrant. To attach a policy across namespaces, use targetSelectors, which can select a whole
Gateway, ListenerSet or HTTPRoute/GRPCRoute in another namespace:
apiVersion:example.extensions.io/v1alpha1kind:RouteContextExamplemetadata:name:cross-ns-policynamespace:policy-nsspec:targetSelectors:- group:gateway.networking.k8s.iokind:HTTPRoutenamespaces:from:All # or Selector / SamematchLabels:team:blue
A cross-namespace selection is only honored when a ReferenceGrant in the target’s namespace permits it.
The grant’s from must match the policy’s group, kind and namespace, and its to must match the target’s group
and kind (optionally a specific name):
apiVersion:gateway.networking.k8s.io/v1beta1kind:ReferenceGrantmetadata:name:allow-extension-policynamespace:route-ns # the namespace of the targeted HTTPRoutespec:from:- group:example.extensions.iokind:RouteContextExamplenamespace:policy-ns # the namespace of the policyto:- group:gateway.networking.k8s.iokind:HTTPRoute
If no matching ReferenceGrant exists, the cross-namespace target is not selected: the policy does not attach, is
not delivered to any hook, and no ancestor status is written. When the policy and target are in the same namespace,
no ReferenceGrant is required.
sectionName targeting (a route rule or a listener) is only available through targetRefs/targetRef, so it is
always same-namespace.
Status reporting
Envoy Gateway records the outcome of attachment in the policy’s status.ancestors conditions. The ancestor is the
Gateway the target resolves to, the ListenerSet itself for a ListenerSet target, or the GatewayClass itself for
a GatewayClass target:
Attached: the policy is delivered to the relevant hook(s) and an Accepted: True condition (reason
Accepted) is set.
sectionName not found: when a policy specifies a sectionName (route rule or listener) that does not exist
on the targeted resource, the policy does not attach and is not delivered to any hook; an Accepted: False
condition with reason TargetNotFound is set.
Unsupported route kind: targeting TCPRoute, UDPRoute, or TLSRoute is not currently supported. The policy
does not attach and an Accepted: False condition with reason Invalid is set.
GatewayClass without mergeGateways: the policy does not attach and an Accepted: False condition with
reason Invalid is set on the GatewayClass ancestor.
GatewayClass with sectionName: the policy does not attach and an Accepted: False condition with reason
Invalid is set; target a Gateway with sectionName instead.
GatewayClass with no listeners: when mergeGateways is enabled but the class currently has no Gateways (or
none of them have listeners), the policy does not attach and an Accepted: False condition with reason
TargetNotFound is set.
Target not found: when the referenced Gateway / ListenerSet / route does not exist (or the Gateway, or the
parent Gateway of the ListenerSet, was not accepted), the
policy is skipped silently and no condition is written, since the target may be created (or become accepted) later.
Configuration
Extensions must specify which hooks they want to use in the extensionManager.hooks configuration:
extensionManager:hooks:xdsTranslator:post:- Route # Enable route modification hook- VirtualHost # Enable virtual host modification hook- HTTPListener # Enable HTTP listener modification hook- Cluster # Enable cluster modification hook- Translation # Enable global translation hook- Secret # Enable secret resolution hook (requires secretResources)# Configure which resources to include in PostTranslateModifyHook# Default: true for clusters and secrets (for backward compatibility)# Default: false for listeners and routes (for backward compatibility)translation:listener:includeAll:trueroute:includeAll:true
To use the Secret hook, register the kinds that Gateway or ListenerSet listeners may reference in
tls.certificateRefs under secretResources:
extensionManager.backendResources registers resource kinds that HTTPRoute backendRefs can
reference as custom backends (for example an S3 bucket or a Lambda function). Envoy Gateway hands
these backendRefs to the extension, which configures their clusters with the Cluster hook.
Custom backends are supported only in HTTPRoute and GRPCRoute backendRefs. TCPRoute, UDPRoute and
TLSRoute backendRefs and policy backendRefs, such as those in ExtAuth, ExtProc or telemetry
sinks, accept only Service, ServiceImport and Backend.
The backend kinds Envoy Gateway resolves itself can’t be registered, and Envoy Gateway fails to
start if backendResources lists any of them:
Group
Kind
"" (core)
Service
multicluster.x-k8s.io
ServiceImport
gateway.envoyproxy.io
Backend
Custom backends are matched by group and kind, so registering one of these wouldn’t add a new
backend type: it would hand every backendRef of that kind in the cluster to the extension. Those
backendRefs would then skip Envoy Gateway’s own validation and endpoint resolution, and the
extension would have to build working clusters for all of them. To change how Envoy Gateway
connects to these backends, use the xDS translator hooks (such as the Cluster or Translation
hook) on the clusters it generates instead.
A custom resource that happens to share a built-in kind name in its own group, such as
custom.example.io/Service, is allowed and is always handed to the extension.
How custom backends are translated
Envoy Gateway treats a custom backendRef like any other backendRef in the rule:
Each backendRef in the rule gets its own cluster, whether it is a custom backend, a Service, a
ServiceImport or a Backend.
A rule with more than one backendRef routes with Envoy weighted_clusters, using the backendRef
weights. A rule with a single backendRef routes to that cluster directly.
The Cluster hook is called once for each custom backend cluster. backend_extension_resources
holds the custom backend resource for that cluster only, plus any resources from the route’s
extensionRef filters.
A custom backendRef with weight 0 gets no cluster and is not passed to the extension.
For example, this rule sends 75% of the traffic to pool-a and 25% to pool-b. Envoy Gateway
generates two clusters and calls the Cluster hook twice, once with pool-a and once with pool-b:
Migrating extensions that expect one cluster per rule
Breaking change
Earlier releases generated a single cluster for each rule with custom backends and called the
Cluster hook once, with every custom backend resource in the rule. The backendRef weights were
ignored, and a rule that mixed a Service or Backend with a custom backend sent all its traffic to
one side.
Check your extension against these cases:
The extension reads one custom backend resource per hook call. No change is needed. The hook
now receives that resource on its own cluster.
The extension loops over backend_extension_resources and configures one cluster for all of
them. Configure the cluster from the single custom backend resource it receives. Resources from
the route’s extensionRef filters are still included, so check the kind of each resource rather
than assuming every entry is a backend.
The extension split the merged cluster itself, for example by building its own weighted
clusters or endpoints from several backend resources. Remove that logic. Envoy Gateway now
creates one cluster per backendRef and routes between them with the backendRef weights.
The extension needs to see several backends together, for example to load balance across
them with its own logic, or to fail over between them. Define a custom resource that lists those
backends, register its kind in backendResources, and reference it from the rule as a single
backendRef. Envoy Gateway then generates one cluster for it and calls the Cluster hook with
that resource, which holds every backend the extension needs. If the extension instead needs to
change how Envoy Gateway’s clusters are combined, use the Translation hook
(PostTranslateModifyHook), which receives all clusters and routes at once.
This task sets up an example extension server that adds the Envoy Proxy Basic Authentication
HTTP filter to all the listeners generated by Envoy Gateway. The example extension server
includes its own CRD which allows defining username/password pairs that will be accepted by
the Envoy Proxy.
Note: Envoy Gateway supports adding Basic Authentication to routes using a SecurityPolicy.
See this task for the preferred way to configure Basic
Authentication.
Quickstart
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Build and run the example Extension Server
Build and deploy the example extension server in the examples/extension-server folder into the cluster
running Envoy Gateway.
Build the extension server image
Note: The provided Makefile builds an image with the name extension-server:latest. You may need to create
a different tag for it in order to allow Kubernetes to pull it correctly.
make image
Publish the extension server image in your docker repository
Configure Envoy Gateway to use the Extension Server
Add the following fragment to Envoy Gateway’s configmap:
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: ConfigMap
metadata:
name: envoy-gateway-config
namespace: envoy-gateway-system
data:
envoy-gateway.yaml: |
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyGateway
provider:
type: Kubernetes
gateway:
controllerName: gateway.envoyproxy.io/gatewayclass-controller
extensionManager:
# Envoy Gateway will watch these resource kinds and use them as extension policies
# which can be attached to Gateway resources.
policyResources:
- group: example.extensions.io
version: v1alpha1
kind: ListenerContextExample
hooks:
# The type of hooks that should be invoked
xdsTranslator:
post:
- HTTPListener
service:
# The service that is hosting the extension server
fqdn:
hostname: extension-server.envoy-gateway-system.svc.cluster.local
port: 5005
EOF
After updating Envoy Gateway’s configmap, restart Envoy Gateway.
Multiple extension servers
Envoy Gateway also supports chaining multiple extension servers. Use the
extensionManagers field (plural) instead of extensionManager:
A few nuances apply when multiple extension managers are configured:
Sequential chaining. Hooks are invoked in the order the servers are
declared. Each server sees the output of the previous one, so mutations
compose.
Resource isolation. Each server only receives the extension resources
whose GVK it declares under resources, policyResources,
backendResources, or secretResources. In the example above a FooFilter is sent to ext-a
but not to ext-b.
The Secret hook does not chain. Only the server that declares the
referenced kind under secretResources is called.
failOpen is per server. Setting failOpen: true on a server causes
Envoy Gateway to skip that server in the chain when its hook returns an
error (or when its gRPC connection cannot be established), while still
invoking the remaining servers. Set service.timeout so that calls to an
unreachable server return an error instead of blocking translation (see
Call timeout).
Unique name required. Every entry in extensionManagers must have a
distinct name. Names surface in error messages as
extension "<name>": <error>.
Mutually exclusive with the singular form.extensionManager and
extensionManagers cannot both be set.
Call timeout
By default, hook calls have no deadline. If the extension server is
unreachable, a call waits for the connection to become ready, which blocks
xDS translation until the server comes back. Because no error is returned,
failOpen never takes effect.
Set service.timeout to bound each hook call. The timeout covers the time
spent waiting for the connection and any retries. When it is exceeded, the
call fails with DEADLINE_EXCEEDED, and Envoy Gateway either skips the server
(failOpen: true) or fails translation (failOpen: false).
Choose a timeout longer than your extension server’s slowest expected
response, including retries.
Testing
Get the Gateway’s address:
exportGATEWAY_HOST=$(kubectl get gateway/eg -o jsonpath='{.status.addresses[0].value}')
The extension server adds the Basic Authentication HTTP filter to all listeners configured by
Envoy Gateway. Initially there are no valid user/password combinations available. Accessing the
example backend should fail with a 401 status:
$ curl -v --header "Host: www.example.com""http://${GATEWAY_HOST}/example"...
> GET /example HTTP/1.1
> Host: www.example.com
> User-Agent: curl/7.81.0
> Accept: */*
>* Mark bundle as not supporting multiuse
< HTTP/1.1 401 Unauthorized
< www-authenticate: Basic realm="http://www.example.com/example"
< content-length: 58
< content-type: text/plain
< date: Mon, 08 Jul 2024 10:53:11 GMT
<
...
User authentication failed. Missing username and password.
...
Add a new Username/Password combination using the example extension server’s CRD:
This task provides instructions for configuring external processing.
External processing calls an external gRPC service to process HTTP requests and responses.
The external processing service can inspect and mutate requests and responses.
Envoy Gateway introduces a new CRD called EnvoyExtensionPolicy that allows the user to configure external processing.
This instantiated resource can be linked to a Gateway and HTTPRoute resource.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
Create a new EnvoyExtensionPolicy resource to configure the external processing service. This EnvoyExtensionPolicy targets the HTTPRoute
“myApp” created in the previous step. It calls the GRPC external processing service “grpc-ext-proc” on port 9002 for
processing.
By default, requests and responses are not sent to the external processor. The processingMode struct is used to define what should be sent to the external processor.
In this example, we configure the following processing modes:
The empty request field configures envoy to send request headers to the external processor.
The response field includes configuration for body processing. As a result, response headers are sent to the external processor. Additionally, the response body is streamed to the external processor.
kubectl get envoyextensionpolicy/ext-proc-example -o yaml
Because the gRPC external processing service is enabled with TLS, a BackendTLSPolicy needs to be created to configure
the communication between the Envoy proxy and the gRPC auth service.
Checkout the Developer Guide to get involved in the project.
2.4.7 - Lua Extensions
This task provides instructions for extending Envoy Gateway with Lua extensions.
Lua extensions allow you to extend the functionality of Envoy Gateway by running custom code against HTTP requests and responses,
without modifying the Envoy Gateway binary. These comparatively light-weight extensions are written in the Lua scripting language using APIs defined here.
Envoy Gateway allows the user to configure Lua extensions using the EnvoyExtensionPolicy CRD.
This instantiated resource can be linked to a Gateway or HTTPRoute resource. If linked to both, the resource linked to the route takes precedence over those linked to Gateway.
Warning
Lua scripts execute inside the Envoy proxy process without strong sandboxing. While Envoy Gateway
sanitizes scripts and restricts the available Lua API surface, the Lua runtime is inherently less
isolated than a dedicated extension process.
When enabling Lua extensions, admins should take additional measures to reduce risk, including:
Using K8s RBAC to restrict who can create or modify EnvoyExtensionPolicy resources with Lua scripts.
Using AdmissionControl tools (e.g. OPA Gatekeeper, Kyverno) to validate and review Lua scripts before they are admitted.
Auditing EnvoyExtensionPolicy resources periodically, and enabling AuditLog for API server operations on these resources.
Not enabling Lua when it is not needed by omitting the enableLua field or setting it to false in the EnvoyGateway configuration.
Enable Lua
Lua extensions are disabled by default. To enable Lua, set enableLua: true in the EnvoyGateway configuration:
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
Inline Lua: The extension defines the Lua script as an inline string.
ValueRef Lua: The extension points to an in-cluster ConfigMap resource that contains the Lua script in it’s data.
The following example demonstrates how to configure an EnvoyExtensionPolicy to attach a Lua extension to a HTTPRoute.
This Lua extension adds a custom header x-lua-custom: FOO to the response.
Lua Extension - Inline
This EnvoyExtensionPolicy configuration defines the Lua script as an inline string.
Save and apply the following resource to your cluster:
---apiVersion:gateway.envoyproxy.io/v1alpha1kind:EnvoyExtensionPolicymetadata:name:lua-inline-testspec:targetRefs:- group:gateway.networking.k8s.iokind:HTTPRoutename:backendlua:- type:Inlineinline:| function envoy_on_response(response_handle)
response_handle:headers():add("x-lua-custom", "FOO")
end
Verify the EnvoyExtensionPolicy status:
kubectl get envoyextensionpolicy/lua-inline-test -o yaml
Lua Extension - ValueRef
This EnvoyExtensionPolicy configuration defines the Lua extension in a ConfigMap resource.
Save and apply the following resources to your cluster:
---apiVersion:gateway.envoyproxy.io/v1alpha1kind:EnvoyExtensionPolicymetadata:name:lua-valueref-testspec:targetRefs:- group:gateway.networking.k8s.iokind:HTTPRoutename:backendlua:- type:ValueRefvalueRef:name:cm-lua-valuerefkind:ConfigMapgroup:v1---apiVersion:v1kind:ConfigMapmetadata:name:cm-lua-valuerefdata:lua:| function envoy_on_response(response_handle)
response_handle:headers():add("x-lua-custom", "FOO")
end
Verify the EnvoyExtensionPolicy status:
kubectl get envoyextensionpolicy/lua-valueref-test -o yaml
Lua Extension - FilterContext
The filterContext field allows you to pass key/value pairs to a shared Lua script, so it can be parameterized differently per route.
The Lua script accesses these values via the filterContext() stream handle API.
This example uses a shared ConfigMap Lua script that reads a configurable header name from filter context and copies its value to the authorization header.
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: ConfigMap
metadata:
name: cm-lua-shared-auth
data:
lua: |
function envoy_on_request(request_handle)
local ctx = request_handle:filterContext()
local token = request_handle:headers():get(ctx:get("token_header"))
if token and token ~= "" then
request_handle:headers():replace("authorization", "Bearer " .. token)
end
end
---
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyExtensionPolicy
metadata:
name: lua-filter-context-test
spec:
targetRefs:
- group: gateway.networking.k8s.io
kind: HTTPRoute
name: backend
lua:
- type: ValueRef
valueRef:
name: cm-lua-shared-auth
kind: ConfigMap
group: v1
filterContext:
token_header: x-api-key
EOF
Save and apply the following resources to your cluster:
---apiVersion:v1kind:ConfigMapmetadata:name:cm-lua-shared-authdata:lua:| function envoy_on_request(request_handle)
local ctx = request_handle:filterContext()
local token = request_handle:headers():get(ctx:get("token_header"))
if token and token ~= "" then
request_handle:headers():replace("authorization", "Bearer " .. token)
end
end---apiVersion:gateway.envoyproxy.io/v1alpha1kind:EnvoyExtensionPolicymetadata:name:lua-filter-context-testspec:targetRefs:- group:gateway.networking.k8s.iokind:HTTPRoutename:backendlua:- type:ValueRefvalueRef:name:cm-lua-shared-authkind:ConfigMapgroup:v1filterContext:token_header:x-api-key
A different route can reuse the same ConfigMap with different filter context values:
This task demonstrates how to deploy an Open Policy Agent (OPA) sidecar inside Envoy Proxy pods created by Envoy Gateway, with Envoy Proxy communicating with OPA over a Unix Domain Socket.
The setup provides these advantages over running OPA as its own Kubernetes service:
Using a sidecar ensures that the OPA is always on the same worker node as Envoy Proxy. This reduces latency and simplifies access control.
Using a Unix Domain Socket avoids TCP/TLS overhead while improving security by avoiding network exposure and reduces latency.
This production-ready approach uses Envoy Gateway’s extension APIs to configure Envoy Proxy’s external authorization and standard Kubernetes API objects to configure OPA’s Envoy External Authorization gRPC plugin.
Note: In this diagram, the Unix Domain Socket is shown outside of the Proxy and OPA containers, but it is actually mounted to both containers.
The example flow on this page will use Envoy to authenticate JWTs and OPA to validate the ISS claim on the JWT. If the ISS matches a configured env var value then requests will be allowed.
Note that the OPA sidecar with Unix Domain Sockets pattern does not require that JWTs be used. Also, simple ISS claim validation could be done more easily using the “authentication” property of the SecurityPolicy spec, but using OPA allows for more complex logic to be applied. See JWT Claim-Based Authorization to see how to use the SecurityPolicy “authentication” property.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Steps overview
Enable the Backend extension API so Envoy can reference a Unix Domain Socket.
Create an OPA policy in a ConfigMap and mount it into an OPA sidecar in the Envoy pods.
Configure the Envoy Proxy pods to have an OPA sidecar
Configure a SecurityPolicy that delegates authorization to OPA via the Unix Domain Socket Backend. For demonstration purposes we’ll also configure JWT authentication.
Create an HTTPRoute that requires protection
Test the configuration
Step 1: Enable the Backend extension API
Enable the Backend API in your Envoy Gateway ConfigMap to allow Envoy to reference Unix Domain Sockets by setting the “enableBackend” property to “true” in the “envoy-gateway-config” ConfigMap:
OLD_CONFIG=$(kubectl get cm envoy-gateway-config -n envoy-gateway-system -o jsonpath='{.data.envoy-gateway\.yaml}')NEW_CONFIG=$(echo"$OLD_CONFIG"| sed "s/extensionApis: {}/extensionApis:\n enableBackend: true/")kubectl create configmap envoy-gateway-config -n envoy-gateway-system \
--from-literal=envoy-gateway.yaml="$NEW_CONFIG"\
--dry-run=client -o yaml | kubectl apply -f -
Ignore the kubectl warning. It happens because kubectl apply expects a “receipt” (the last-applied-configuration annotation) to be present on the resource so it can track changes over time. If the ConfigMap was originally created using kubectl create (without --save-config) or by a Helm chart, that receipt is missing. kubectl is simply telling you that it’s adding that receipt now.
Restart the Envoy Gateway deployment to apply the updated configuration:
The Envoy Proxy pod will be restarted later in this guide.
Step 2: Create the OPA policy
Create a ConfigMap with a Rego policy that OPA will load. This example reads the “ALLOWED_ISS” environment variable and compares it to the JWT ISS claim, allowing the request only if they match.
On MacOS you can apply that by copying it and running pbpaste | kubectl apply -f -.
In this policy we extract a x-jwt-iss header from the request. That header is not automatically available on ext_authz filter requests. We will configure Envoy to add that header from the decoded JWT. That configuration happens in the SecurityPolicy in step 4.
Step 3: Configure the Envoy Proxy pods to have an OPA sidecar
Create an EnvoyProxy resource that mounts the OPA policy ConfigMap, shares a Unix Domain Socket between Envoy and OPA, and configures the “ext_authz” filter order so OPA receives JWT headers from the JWT authentication filter.
apiVersion:gateway.envoyproxy.io/v1alpha1kind:EnvoyProxymetadata:name:egnamespace:envoy-gateway-systemspec:# Ensure ext_authz runs after jwt_authn so that OPA sees the JWT-derived headers# configured in the SecurityPolicy in step 4filterOrder:- name:envoy.filters.http.ext_authzafter:envoy.filters.http.jwt_authnprovider:type:Kuberneteskubernetes:envoyDeployment:patch:type:StrategicMergevalue:spec:template:spec:volumes:# Shared Unix Domain Socket volume for communication between Envoy# and OPA. This will be mounted in both containers.- name:opa-unix-socketemptyDir:{}# OPA Rego policy file from ConfigMap. This will be mounted# in the OPA container.- name:opa-policyconfigMap:name:opa-policycontainers:# Add the Unix Domain Socket volume to the existing envoy# proxy container named "envoy".- name:envoyvolumeMounts:# Mount the Unix Domain Socket volume in the Envoy container- name:opa-unix-socketmountPath:/shared/opa# Create the OPA sidecar container- name:opa# OPA image tag format:# - "x.y.z": OPA version# - "envoy": includes OPA's Envoy External Authorization gRPC plugin# - "5": plugin version# - "static": static build (no glibc dependency, smaller image)image:openpolicyagent/opa:1.10.1-envoy-5-staticargs:- "run"- "--server"# In addition to listening on the Unix Domain Socket, we'll listen# on port 8181 for k8s probes- "--addr=0.0.0.0:8181"# Configure OPA's Envoy external authorization plugin to listen on a Unix Domain Socket- "--set=plugins.envoy_ext_authz_grpc.addr=unix:///shared/opa/opa.sock"# In the OPA policy we defined the policy as being in a# "envoy.authz" package and set the "allow" variable# based on the policy decision. Here we tell the plugin# to check that value.- "--set=plugins.envoy_ext_authz_grpc.query=data.envoy.authz.allow"- "--ignore=.*"# You can set log-level to "debug" for detailed request logging- "--log-level=error"# Tell OPA where to find the policy file- "/policy/policy.rego"env:# Environment variable used by the OPA policy to validate the JWT issuer- name:ALLOWED_ISSvalue:"https://example.com"ports:# Port for health checks only; gRPC server listens on the Unix Domain Socket- name:httpcontainerPort:8181protocol:TCPvolumeMounts:# Mount the Unix Domain Socket volume in the OPA container- name:opa-unix-socketmountPath:/shared/opa# Mount the OPA Rego policy from ConfigMap- name:opa-policymountPath:/policyreadOnly:truelivenessProbe:httpGet:path:/healthport:8181initialDelaySeconds:5periodSeconds:10timeoutSeconds:3failureThreshold:3readinessProbe:httpGet:path:/health?bundle=trueport:8181initialDelaySeconds:5periodSeconds:5timeoutSeconds:3failureThreshold:3securityContext:# Use the same user ID as the Envoy container (65532) so both containers can access the socket# The user ID was found by running "docker pull docker.io/envoyproxy/gateway:v<version> && docker inspect docker.io/envoyproxy/gateway:v<version>"runAsUser:65532allowPrivilegeEscalation:falseresources:# Adjust as necessaryrequests:cpu:100mmemory:128Milimits:memory:512Mi
This patch adds an OPA sidecar container to the Envoy pods, creates a shared Unix Domain Socket at /shared/opa/opa.sock, and configures OPA to listen only on this socket instead of TCP. It sets an ALLOWED_ISS property that OPA will use to validate the request. We purposefully set the wrong value here so we can see the response when the wrong ISS is used. We’ll set it to the correct value later.
Tell Envoy Gateway to use this EnvoyProxy spec by patching the GatewayClass.
This will cause the Envoy Proxy pod to be replaced with the new config.
Step 4: Connect Envoy to OPA with a SecurityPolicy and Backend
Create a Unix Domain Socket SecurityPolicy and a Backend that authenticates JWTs, maps the ISS claims to the x-jwt-iss header, and delegates authorization to OPA.
apiVersion:gateway.envoyproxy.io/v1alpha1kind:SecurityPolicymetadata:name:opa-jwt-authz# The SecurityPolicy must be in the same namespace as the HTTPRoutes that it# will apply tonamespace:defaultspec:targetSelectors:- group:gateway.networking.k8s.iokind:HTTPRoutematchLabels:auth:opa-jwtjwt:providers:- name:my-jwt-validator# Verify that the JWT is signed with the correct keyremoteJWKS:uri:https://raw.githubusercontent.com/envoyproxy/gateway/refs/heads/main/examples/kubernetes/jwt/jwks.json# Add the JWT ISS claim to request to the headers sent to OPA. Note: this only works# for string claims, not arrays. For example, the "aud" claim cannot be passed# this way because the JWT spec defines it as an array.claimToHeaders:- header:x-jwt-issclaim:iss# Delegate authorization to an external program after JWT verificationextAuth:grpc:backendRefs:# Reference the OPA Unix Domain Socket backend, which is the next API object in this code block- group:gateway.envoyproxy.iokind:Backendname:opa-unix-socket# Headers to send to OPA for authorization decisions. This should match the# "claimToHeaders" values above.headersToExtAuth:- x-jwt-iss---apiVersion:gateway.envoyproxy.io/v1alpha1kind:Backendmetadata:name:opa-unix-socket# The Backend must be in the same namespace as the SecurityPolicynamespace:defaultspec:endpoints:# This configures Envoy proxy to send external auth requests to the Unix Domain Socket- unix:path:/shared/opa/opa.sock
Step 5: Configure route to use the OPA authorization
Attach the policy by labeling routes that require authorization. This HTTPRoute uses the backend service installed in the Quick Start:
exportGATEWAY_HOST=$(kubectl get gateway/eg -o jsonpath='{.status.addresses[0].value}')exportENVOY_SERVICE=$(kubectl get svc -n envoy-gateway-system --selector=gateway.envoyproxy.io/owning-gateway-namespace=default,gateway.envoyproxy.io/owning-gateway-name=eg -o jsonpath='{.items[0].metadata.name}')exportVALID_TOKEN="eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6ImI1MjBiM2MyYzRiZDc1YTEwZTljZWJjOTU3NjkzM2RjIn0.eyJpc3MiOiJodHRwczovL2Zvby5iYXIuY29tIiwic3ViIjoiMTIzNDU2Nzg5MCIsInVzZXIiOnsibmFtZSI6IkpvaG4gRG9lIiwiZW1haWwiOiJqb2huLmRvZUBleGFtcGxlLmNvbSIsInJvbGVzIjpbImFkbWluIiwiZWRpdG9yIl19LCJwcmVtaXVtX3VzZXIiOnRydWUsImlhdCI6MTUxNjIzOTAyMiwic2NvcGUiOiJyZWFkIGFkZCBkZWxldGUgbW9kaWZ5In0.P36iAlmiRCC79OiB3vstF5Q_9OqUYAMGF3a3H492GlojbV6DcuOz8YIEYGsRSWc-BNJaBKlyvUKsKsGVPtYbbF8ajwZTs64wyO-zhd2R8riPkg_HsW7iwGswV12f5iVRpfQ4AG2owmdOToIaoch0aym89He1ZzEjcShr9olgqlAbbmhnk-namd1rP-xpzPnWhhIVI3mCz5hYYgDTMcM7qbokM5FzFttTRXAn5_Luor23U1062Ct_K53QArwxBvwJ-QYiqcBycHf-hh6sMx_941cUswrZucCpa-EwA3piATf9PKAyeeWHfHV9X-y8ipGOFg3mYMMVBuUZ1lBkJCik9f9kboRY6QzpOISARQj9PKMXfxZdIPNuGmA7msSNAXQgqkvbx04jMwb9U7eCEdGZztH4C8LhlRjgj0ZdD7eNbRjeH2F6zrWyMUpGWaWyq6rMuP98W2DWM5ZflK6qvT1c7FuFsWPvWLkgxQwTWQKrHdKwdbsu32Sj8VtUBJ0-ddEb"
If Envoy is not running behind a load balancer, then you’ll have to start port forwarding whenever the Envoy Proxy pod is reconfigured and the proxy pods are replaced:
Test with a valid JWT that has the wrong ISS claim
Earlier, we configured the “ALLOWED_ISS” env var on the proxy pods to be “https://example.com”, but the JWT in the “VALID_TOKEN” env var has an ISS claim of “https://foo.bar.com”.
This task explains how to configure Envoy Gateway to defer Envoy proxy and rate
limit infrastructure management to a remote service of your own. With the Remote
infrastructure provider, Envoy Gateway translates Gateway API resources into its
into an infrastructure IR format and forwards it over gRPC to a provider you
operate. The provider is then responsible for reconciling the data plane.
This is the right choice when the built-in Kubernetes infrastructure provider
doesn’t fit your environment. Common cases include running proxies in a
different cluster from the control plane, deploying onto a non-Kubernetes
substrate (VMs, an internal scheduler, etc.), or imposing custom organizational
rules on how proxy workloads are shaped.
Note: Most users should use the built-in Kubernetes infrastructure provider.
The Remote provider is an extension point; running it means owning the lifecycle
of every proxy and rate limit deployment yourself.
Security Warning
Security Warning
The remote infrastructure
provider is a privileged component. It receives the complete Infrastructure IR
for every Gateway managed by Envoy Gateway and is trusted to faithfully
reconcile it. A compromised or misconfigured provider can stop creating proxies,
deploy proxies with attacker-controlled configuration, or expose the data plane
to networks it shouldn’t reach.
When deploying a remote infrastructure provider, you should:
Run the provider as a sidecar of envoy-gateway, or otherwise on a private
channel that is not reachable from untrusted networks. The reference
deployment uses a Unix domain socket on a shared volume.
Restrict the provider’s permissions to the minimum needed to manage the proxy
data plane.
Audit the provider on the same cadence as Envoy Gateway itself; bumping Envoy
Gateway may change the IR shape.
How it works
When the Remote provider is enabled, Envoy Gateway defers infrastructure
management using an gRPC client to send updates to your provider. For every
reconcile that mutates a proxy or rate limit deployment, Envoy Gateway issues a
corresponding RPC carrying the IR as structured protobuf data.
The service contract is defined in proto/remoteinfra/service.proto:
The proxy RPCs carry the IR as a structured Infra message that mirrors
internal/ir/infra.go, including proxy metadata (labels, annotations, and the
owner reference) and each metric sink’s destination (endpoints and upstream
TLS). Most fields are typed protobuf fields; the proxy config (an EnvoyProxy
resource) is the only field carried as JSON-encoded bytes, because that CRD
schema is large and evolves independently of this contract. The rate limit RPCs
are parameterless. The provider is expected to be idempotent — Envoy Gateway
calls the CreateOrUpdate RPCs every time the desired state changes and may
retry on transient errors.
Configuration
The Remote provider is selected under provider.custom.infrastructure in the
EnvoyGateway config. The service field is required and uses the standard
[ExtensionService] shape, so you can reach the provider over a Unix socket, a
hostname, or an IP.
When TLS is configured, Envoy Gateway verifies the server certificate against
the CA in the referenced Secret. Add clientCertificateRef if your provider
requires mTLS.
Rate limit service address
The Remote provider tells Envoy Gateway what rate limit infrastructure to
stand up via the CreateOrUpdateRateLimitInfra RPC, but Envoy proxies still
need to know where to send rate limit checks. Set rateLimit.url on the
EnvoyGateway config to the address your provider exposes. The value must be a
grpc:// URL with an explicit host and port:
If rateLimit.url is unset, Envoy Gateway falls back to the address of the
Service the Kubernetes infrastructure manager would have created.
Quickstart
This walks through deploying the example provider in examples/remote-infra as
a native sidecar of the envoy-gateway Deployment, communicating over a Unix
domain socket. The example provider reconciles a Deployment and a Service
per Gateway and is intended as a starting point — not a production-ready
provider.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Build and load the example provider image
The example lives in examples/remote-infra/ and ships with a Makefile target
that builds a multi-arch image tagged envoyproxy/gateway-remote-infra:latest.
make -C examples/remote-infra docker-buildx
If you’re running on kind, load the image into the cluster so the sidecar can
pull it:
The provider needs to share a volume with envoy-gateway so they can talk over
a UDS, and it needs to start before envoy-gateway does. Native sidecars give
us both for free on Kubernetes 1.29+.
cat <<'EOF' | kubectl patch deployment envoy-gateway -n envoy-gateway-system --patch-file /dev/stdin
apiVersion: apps/v1
kind: Deployment
metadata:
name: envoy-gateway
namespace: envoy-gateway-system
spec:
template:
spec:
securityContext:
runAsNonRoot: true
runAsUser: 65532
runAsGroup: 65532
# fsGroup ensures the shared emptyDir is group-owned by 65532 so the
# non-root sidecar can create the UDS socket file in it.
fsGroup: 65532
volumes:
- name: remote-infra-socket
emptyDir: {}
containers:
- name: envoy-gateway
volumeMounts:
- name: remote-infra-socket
mountPath: /var/run/remote-infra
initContainers:
- name: remote-infra
image: envoyproxy/gateway-remote-infra:latest
imagePullPolicy: IfNotPresent
restartPolicy: Always
args:
- --socket-path=/var/run/remote-infra/server.sock
env:
- name: NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
# Gates startup of envoy-gateway: it will not start until the UDS
# socket exists.
startupProbe:
exec:
command: ["test", "-S", "/var/run/remote-infra/server.sock"]
periodSeconds: 1
failureThreshold: 30
volumeMounts:
- name: remote-infra-socket
mountPath: /var/run/remote-infra
EOF
Switch Envoy Gateway to the Remote provider
Patch the envoy-gateway-config ConfigMap to dial the sidecar over the shared
socket:
You should see Creating proxy infra [...] lines as Gateways are reconciled.
The example provider creates a Deployment and Service for each Gateway in
the same namespace as Envoy Gateway; check them with:
kubectl get deploy,svc -n envoy-gateway-system -l app.kubernetes.io/managed-by=envoy-gateway
Writing your own provider
The example in examples/remote-infra/ is a useful starting point but only
renders a Deployment and a Service. A production-grade provider will
typically need to:
Be idempotent. Envoy Gateway calls CreateOrUpdate whenever the IR
changes, which in practice can be many times per second during churn. The
example uses a server-side apply pattern; you should do the same or its
equivalent for your data plane.
Plan for IR evolution. The IR is JSON for forward-compatibility, but new
fields will be added as Envoy Gateway evolves. Design your provider to ignore
unknown fields rather than fail on them.
Communicate data plane status. Envoy Gateway needs metadata about your
data plane, such as the DNS address to find the fleet at. Make sure your
provider communicates that information back via a Service object. The example
infra server provides a basic example.
The IR types are defined in internal/ir/. The ir.Infra value Envoy Gateway
sends is documented by the Go types ir.ProxyInfra and ir.RateLimitInfra.
2.4.10 - Wasm Extensions
This task provides instructions for extending Envoy Gateway with WebAssembly (Wasm) extensions.
Wasm extensions allow you to extend the functionality of Envoy Gateway by running custom code against HTTP requests and responses,
without modifying the Envoy Gateway binary. These extensions can be written in any language that compiles to Wasm, such as C++, Rust, AssemblyScript, or TinyGo.
Envoy Gateway introduces a new CRD called EnvoyExtensionPolicy that allows the user to configure Wasm extensions.
This instantiated resource can be linked to a Gateway and HTTPRoute resource.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Configuration
Envoy Gateway supports three types of Wasm extensions:
HTTP Wasm Extension: The Wasm extension is fetched from a remote URL.
Image Wasm Extension: The Wasm extension is packaged as an OCI image and fetched from an image registry.
Registered Wasm module: The Wasm extension is loaded from a module registered on EnvoyProxy (spec.wasmModules). Today only a Local filesystem path is supported. Omit code and set wasm[].name to the registered module name.
The following example demonstrates how to configure an EnvoyExtensionPolicy to attach a Wasm extension to an EnvoyExtensionPolicy .
This Wasm extension adds a custom header x-wasm-custom: FOO to the response.
HTTP Wasm Extension
This EnvoyExtensionPolicy configuration fetches the Wasm extension from an HTTP URL.
Register the module on the EnvoyProxy attached to the Gateway, then omit code and set wasm[].name to that module name on the EnvoyExtensionPolicy. Envoy Gateway does not place Local modules on the proxy; provision them with a custom Envoy image or a volume mount. Local modules skip the control-plane download path, which avoids a fail-closed load window when the file is already on the proxy.
Envoy Gateway translates Gateway API resources to Envoy XDS resources. In this translation process, Envoy Gateway annotates XDS resources with additional metadata from their origin Gateway API resources.
Gateway API Metadata includes:
K8s Resource Kinds, Names and Namespaces.
K8s Resource Annotations with the gateway.envoyproxy.io/ prefix.
K8s Resource SectionNames (when applicable, e.g. for Route rules and Listeners).
Gateway API Metadata is added to XDS resources using envoy’s Static Metadata under metadata.filter_metadata.envoy-gateway.resources. Currently, resources only contains the primary origin resource.
However, in the future, additional relevant resources (e.g. policies, filters attached to the primary origin resources) may be added.
Supported Resources
Currently, the following mapping of Gateway API metadata to XDS metadata are supported:
Observability: Envoy proxy access logs can be enriched with Gateway-API resource context and custom annotations, creating an association with relevant Application Developers personas.
Troubleshooting: users and tools that analyze the envoy proxy XDS config can identify the Gateway API resources that lead to the XDS configuration’s creation.
Extensibility:
Envoy Gateway Extension Servers can leverage Gateway API metadata as additional context annotating XDS resources sent for mutation.
Envoy Proxy extensions can leverage XDS metadata as additional context when processing traffic:
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Install Add-ons
Envoy Gateway provides an add-ons Helm chart to simplify the installation of observability components. The documentation for the add-ons chart can be found
here.
Follow the instructions below to install the add-ons Helm chart.
Check out the Gateway Exported Metrics section to learn more about the metrics exported by the Envoy Gateway.
2.5.3 - Gateway Exported Metrics
The Envoy Gateway provides a collection of self-monitoring metrics in Prometheus format.
These metrics allow monitoring of the behavior of Envoy Gateway itself (as distinct from that of the EnvoyProxy it managed).
EnvoyProxy Metrics
For EnvoyProxy Metrics, please refer to the EnvoyProxy Metrics to learn more.
Watching Components
The Resource Provider, xDS Translator and Infra Manager etc. are key components that made up of Envoy Gateway,
they all follow the design of Watching Components.
Envoy Gateway collects the following metrics in Watching Components:
Name
Description
watchable_subscribe_duration_seconds
How long in seconds a subscribed watchable queue is handled.
watchable_subscribe_total
Total number of subscribed watchable queue.
watchable_panics_recovered_total
Total recovered panics in the watchable infrastructure.
watchable_publish_total
Total number of published event to watchable queue.
Each metric includes the runner label to identify the corresponding components,
the relationship between label values and components is as follows:
Value
Components
gateway-api
Gateway API Translator
infrastructure
Infrastructure Manager
xds-server
xDS Server
xds-translator
xDS Translator
global-ratelimit
Global RateLimit xDS Translator
Metrics may include one or more additional labels, such as message, status and reason etc.
Status Updater
Envoy Gateway monitors the status updates of various resources (like GatewayClass, Gateway and HTTPRoute etc.) through Status Updater.
Envoy Gateway collects the following metrics in Status Updater:
Name
Description
status_update_total
Total number of status update by object kind.
status_update_duration_seconds
How long a status update takes to finish.
Each metric includes kind label to identify the corresponding resources.
xDS Server
Envoy Gateway monitors the cache and xDS connection status in xDS Server.
Envoy Gateway collects the following metrics in xDS Server:
Name
Description
xds_snapshot_create_total
Total number of xds snapshot cache creates.
xds_snapshot_update_total
Total number of xds snapshot cache updates by node id.
xds_stream_duration_seconds
How long a xds stream takes to finish.
xds_nack_total
Total number of xds updates rejected (NACKed) by Envoy, by node id and resource type.
For xDS snapshot cache update and xDS stream connection status, each metric includes nodeID label to identify the connection peer.
For xDS stream connection status, each metric also includes streamID label to identify the connection stream, and isDeltaStream label to identify the delta connection stream.
Infrastructure Manager
Envoy Gateway monitors the apply (create or update) and delete operations in Infrastructure Manager.
Envoy Gateway collects the following metrics in Infrastructure Manager:
Name
Description
resource_apply_total
Total number of applied resources.
resource_apply_duration_seconds
How long in seconds a resource be applied successfully.
resource_delete_total
Total number of deleted resources.
resource_delete_duration_seconds
How long in seconds a resource be deleted successfully.
Each metric includes the kind label to identify the corresponding resources being applied or deleted by Infrastructure Manager.
Metrics may also include name and namespace label to identify the name and namespace of corresponding Infrastructure Manager.
Wasm
Envoy Gateway monitors the status of Wasm remote fetch cache.
Name
Description
wasm_cache_entries
Number of Wasm remote fetch cache entries.
wasm_cache_lookup_total
Total number of Wasm remote fetch cache lookups.
wasm_remote_fetch_total
Total number of Wasm remote fetches and results.
For metric wasm_cache_lookup_total, we are using hit label (boolean) to indicate whether the Wasm cache has been hit.
Topology Injector MutatingWebhookConfiguration
Envoy Gateway monitors the status of the TopologyInjector webhook which injects node topology information to EnvoyProxy pods.
Name
Description
topology_injector_webhook_events_total
Total number of topology injector webhook events.
This metrics provides information on whether a webhook request was successful, failed, or a no-op.
2.5.4 - Gateway Observability
Envoy Gateway provides observability for the ControlPlane and the underlying EnvoyProxy instances.
This task show you how to config gateway control-plane observability, includes metrics.
Prerequisites
Install Envoy Gateway
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Install Add-ons
Envoy Gateway provides an add-ons Helm chart to simplify the installation of observability components. The documentation for the add-ons chart can be found
here.
Follow the instructions below to install the add-ons Helm chart.
The default installation of Envoy Gateway installs a default EnvoyGateway configuration and attaches it
using a ConfigMap. In this section, we will update this resource to enable various ways to retrieve metrics
from Envoy Gateway.
After updating the ConfigMap, you will need to wait the configuration kicks in. You can force the configuration to be reloaded by restarting the envoy-gateway deployment.
After updating the ConfigMap, you will need to wait the configuration kicks in. You can force the configuration to be reloaded by restarting the envoy-gateway deployment.
exportOTEL_POD_NAME=$(kubectl get pod -n monitoring --selector=app.kubernetes.io/name=opentelemetry-collector -o jsonpath='{.items[0].metadata.name}')kubectl port-forward pod/$OTEL_POD_NAME -n monitoring 19001:19001
# check metrics curl localhost:19001/metrics
2.5.5 - Proxy Access Logs
Envoy Gateway provides observability for the ControlPlane and the underlying EnvoyProxy instances.
This task show you how to config proxy access logs.
Prerequisites
Install Envoy Gateway
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Install Add-ons
Envoy Gateway provides an add-ons Helm chart to simplify the installation of observability components. The documentation for the add-ons chart can be found
here.
Follow the instructions below to install the add-ons Helm chart.
Envoy Gateway can send logs to a backend implemented gRPC access log service proto.
There’s an example service here, which simply count the log and export to prometheus endpoint.
The following configuration sends logs to the gRPC access log service:
Envoy Gateway provides additional metadata about the K8s resources that were translated to certain envoy resources.
For example, details about the HTTPRoute and GRPCRoute (kind, group, name, namespace and annotations) are available
for access log formatter using the METADATA operator.
To enrich logs, users can add log operator that refer to XDS metadata, such as:
If traffic is not matched by any Route known to Envoy, the Listener would emit the access log instead
Users may wish to customize this behavior:
Emit Access Logs by all Listeners for all traffic with specific settings
Do not emit Route-oriented access logs when a route is not matched.
To achieve this, users can select if Access Log settings follow the default behavior or apply specifically to
Routes or Listeners by specifying the setting’s type.
Note: When users define their own Access Log settings (with or without a type), the default Envoy Gateway
file access log is no longer configured. It can be re-enabled explicitly by adding empty settings for the desired components.
In the following example:
Route Access logs would use the default Envoy Gateway format and sink
Listener Access logs are customized to report transport-level failures and connection attributes
Note:EnvoyProxy.spec.telemetry.healthCheckLog applies to xRoute-backed clusters only
(route destination clusters, tracing backends, and access log backends).
For technical backends — ext-auth, ext-proc, JWT/OIDC remote JWKS, and OIDC token endpoints —
configure HC event logging directly in their backendSettings.healthCheck.active.healthCheckLog
field (on EnvoyExtensionPolicy or SecurityPolicy).
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Configure Active Health Checks
Health check event logs require active health checks to be running.
Configure a BackendTrafficPolicy targeting your HTTPRoute with an active health
check. The example below polls /healthz every three seconds:
Health check events will now appear in the Envoy proxy container’s standard output
(when using the default sink or path: /dev/stdout)
in JSON format, for example:
When matches is omitted (the default), all health check probe outcomes are
logged. To log only specific outcomes, set matches to one or more values;
they are ORed together. At least one failure variant and one success variant must
be specified together.
Value
Logged when
Failure
Every failed probe, regardless of current health state
FailureSeriesStart
Only the first failed probe of a consecutive failure run (starts a potential healthy→unhealthy transition)
Success
Every successful probe, regardless of current health state
HealthyTransition
First success of a consecutive success run, and when the host reaches the healthy threshold (transitions back to healthy)
To log only on state transitions (the most conservative setting):
The EnvoyProxy-level healthCheckLog applies to all xRoute-backed clusters. To override it for a specific BackendTrafficPolicy target — set healthCheckLog directly in the BackendTrafficPolicy’s healthCheck.active:
The healthCheckLog in a BackendTrafficPolicy takes precedence over the EnvoyProxy.spec.telemetry.healthCheckLog for that specific cluster.
HC Logging for Technical Backends (ext-proc, ext-auth, etc.)
For backends managed by EnvoyExtensionPolicy or SecurityPolicy — such as ext-proc, ext-auth, or JWT/OIDC providers — configure HC event logging directly in backendSettings.healthCheck.active.healthCheckLog:
The per-backend healthCheckLog takes precedence over the gateway-level EnvoyProxy.spec.telemetry.healthCheckLog for that specific cluster.
Verify
Trigger a health check failure (e.g. by scaling the backend deployment to zero
replicas) and confirm events appear. The location depends on the configured sink:
Default sink or path: /dev/stdout — events appear in the Envoy container logs:
Envoy Gateway offers observability for both the Control Plane and the underlying Envoy Proxy instances.
This task shows you how to configure proxy metrics.
Prerequisites
Install Envoy Gateway
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Install Add-ons
Envoy Gateway provides an add-ons Helm chart to simplify the installation of observability components. The documentation for the add-ons chart can be found
here.
Follow the instructions below to install the add-ons Helm chart.
If you are only using the OpenTelemetry sink, you might want to set the telemetry.metrics.prometheus.disable to true
in the EnvoyProxy CRD as shown in the following command.
If you already run Prometheus via the Prometheus Operator (for example through
kube-prometheus-stack) you do not need the bundled Prometheus from gateway-addons-helm. Disable it as shown
above and have your existing Prometheus discover the proxy pods by applying a PodMonitor that targets the
metrics port served by the Envoy proxy at /stats/prometheus:
The PodMonitor selects pods labelled app.kubernetes.io/name=envoy and app.kubernetes.io/component=proxy
in any namespace (Envoy Gateway places proxy pods in envoy-gateway-system by default but the namespace can be
customised via the EnvoyProxy resource), and scrapes the metrics port that Envoy exposes for the
Prometheus admin endpoint.
The Prometheus Operator only watches PodMonitor and ServiceMonitor resources that match the
podMonitorSelector / podMonitorNamespaceSelector configured on your Prometheus custom resource. If the
target labels do not match the defaults set by your chart, override the PodMonitormetadata.labels to add
the label your Prometheus selects on (commonly release: <helm-release-name> for kube-prometheus-stack).
OpenTelemetry Metrics
Envoy Gateway can export metrics to an OpenTelemetry sink. Use the following command to send metrics to the
OpenTelemetry Collector. Ensure that the OpenTelemetry components are enabled,
as mentioned in the Prerequisites.
Temporarily enable the debug exporter in the OpenTelemetry Collector
to view metrics in the pod logs using the following command. Debug exporter is enabled for demonstration purposes and
should not be used in production.
Envoy Gateway provides observability for the ControlPlane and the underlying EnvoyProxy instances.
This task show you how to config proxy tracing.
Prerequisites
Install Envoy Gateway
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Install Add-ons
Envoy Gateway provides an add-ons Helm chart to simplify the installation of observability components. The documentation for the add-ons chart can be found
here.
Follow the instructions below to install the add-ons Helm chart.
TEMPO_IP=$(kubectl get svc tempo -n monitoring -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
Traces
By default, Envoy Gateway doesn’t send traces to any sink.
You can enable traces by setting the telemetry.tracing in the EnvoyProxy CRD.
Currently, Envoy Gateway support OpenTelemetry, Zipkin and Datadog tracer.
Tracing Provider
The following configurations show how to apply proxy with different providers:
kubectl apply -f - <<EOF
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
name: eg
spec:
controllerName: gateway.envoyproxy.io/gatewayclass-controller
parametersRef:
group: gateway.envoyproxy.io
kind: EnvoyProxy
name: otel
namespace: envoy-gateway-system
---
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyProxy
metadata:
name: otel
namespace: envoy-gateway-system
spec:
telemetry:
tracing:
# sample 100% of requests
samplingRate: 100
provider:
backendRefs:
- name: otel-collector
namespace: monitoring
port: 4317
type: OpenTelemetry
customTags:
# This is an example of using a literal as a tag value
provider:
type: Literal
literal:
value: "otel"
"k8s.pod.name":
type: Environment
environment:
name: ENVOY_POD_NAME
defaultValue: "-"
"k8s.namespace.name":
type: Environment
environment:
name: ENVOY_POD_NAMESPACE
defaultValue: "envoy-gateway-system"
# This is an example of using a header value as a tag value
header1:
type: RequestHeader
requestHeader:
name: X-Header-1
defaultValue: "-"
EOF
kubectl apply -f - <<EOF
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
name: eg
spec:
controllerName: gateway.envoyproxy.io/gatewayclass-controller
parametersRef:
group: gateway.envoyproxy.io
kind: EnvoyProxy
name: zipkin
namespace: envoy-gateway-system
---
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyProxy
metadata:
name: zipkin
namespace: envoy-gateway-system
spec:
telemetry:
tracing:
# sample 100% of requests
samplingRate: 100
provider:
backendRefs:
- name: otel-collector
namespace: monitoring
port: 9411
type: Zipkin
zipkin:
enable128BitTraceId: true
customTags:
# This is an example of using a literal as a tag value
provider:
type: Literal
literal:
value: "zipkin"
"k8s.pod.name":
type: Environment
environment:
name: ENVOY_POD_NAME
defaultValue: "-"
"k8s.namespace.name":
type: Environment
environment:
name: ENVOY_POD_NAMESPACE
defaultValue: "envoy-gateway-system"
# This is an example of using a header value as a tag value
header1:
type: RequestHeader
requestHeader:
name: X-Header-1
defaultValue: "-"
EOF
kubectl apply -f - <<EOF
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
name: eg
spec:
controllerName: gateway.envoyproxy.io/gatewayclass-controller
parametersRef:
group: gateway.envoyproxy.io
kind: EnvoyProxy
name: datadog
namespace: envoy-gateway-system
---
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyProxy
metadata:
name: datadog
namespace: envoy-gateway-system
spec:
telemetry:
tracing:
# sample 100% of requests
samplingRate: 100
provider:
backendRefs:
- name: datadog-agent
namespace: monitoring
port: 8126
type: Datadog
customTags:
# This is an example of using a literal as a tag value
provider:
type: Literal
literal:
value: "datadog"
"k8s.pod.name":
type: Environment
environment:
name: ENVOY_POD_NAME
defaultValue: "-"
"k8s.namespace.name":
type: Environment
environment:
name: ENVOY_POD_NAMESPACE
defaultValue: "envoy-gateway-system"
# This is an example of using a header value as a tag value
header1:
type: RequestHeader
requestHeader:
name: X-Header-1
defaultValue: "-"
EOF
Envoy Gateway use 100% sample rate, which means all requests will be traced.
This may cause performance issues when traffic is very high, you can adjust
the sample rate by setting the telemetry.tracing.samplingRate in the EnvoyProxy CRD.
The following configurations show how to apply proxy with 1% sample rates:
kubectl apply -f - <<EOF
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
name: eg
spec:
controllerName: gateway.envoyproxy.io/gatewayclass-controller
parametersRef:
group: gateway.envoyproxy.io
kind: EnvoyProxy
name: otel
namespace: envoy-gateway-system
---
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyProxy
metadata:
name: otel
namespace: envoy-gateway-system
spec:
telemetry:
tracing:
# sample 1% of requests
samplingRate: 1
provider:
backendRefs:
- name: otel-collector
namespace: monitoring
port: 4317
type: OpenTelemetry
customTags:
# This is an example of using a literal as a tag value
provider:
type: Literal
literal:
value: "otel"
"k8s.pod.name":
type: Environment
environment:
name: ENVOY_POD_NAME
defaultValue: "-"
"k8s.namespace.name":
type: Environment
environment:
name: ENVOY_POD_NAMESPACE
defaultValue: "envoy-gateway-system"
# This is an example of using a header value as a tag value
header1:
type: RequestHeader
requestHeader:
name: X-Header-1
defaultValue: "-"
EOF
If you want the sample rate to less than 1%, you can use the telemetry.tracing.samplingFraction field in the EnvoyProxy CRD.
kubectl apply -f - <<EOF
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
name: eg
spec:
controllerName: gateway.envoyproxy.io/gatewayclass-controller
parametersRef:
group: gateway.envoyproxy.io
kind: EnvoyProxy
name: otel
namespace: envoy-gateway-system
---
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyProxy
metadata:
name: otel
namespace: envoy-gateway-system
spec:
telemetry:
tracing:
# sample 0.1% of requests
samplingFraction:
numerator: 1
denominator: 1000
provider:
backendRefs:
- name: otel-collector
namespace: monitoring
port: 4317
type: OpenTelemetry
customTags:
# This is an example of using a literal as a tag value
provider:
type: Literal
literal:
value: "otel"
"k8s.pod.name":
type: Environment
environment:
name: ENVOY_POD_NAME
defaultValue: "-"
"k8s.namespace.name":
type: Environment
environment:
name: ENVOY_POD_NAMESPACE
defaultValue: "envoy-gateway-system"
# This is an example of using a header value as a tag value
header1:
type: RequestHeader
requestHeader:
name: X-Header-1
defaultValue: "-"
EOF
Tempo and appProtocol
When using Grafana Tempo it is important to note that the tempo-distributed Helm chart
will omit a appProtocol in the tempo-distributor Service. Without this protocol hint, Envoy will send traces to Tempo using the wrong protocol: HTTP, instead of GRPC.
You can add the protocol hint to the tempo-distributor Service, by supplying these values to the “tempo-distributed” Helm chart:
distributor:appProtocol:grpc:grpc=======### SamplerFor OpenTelemetry tracing, you can configure the sampler using the `openTelemetry.sampler` field.When a sampler is configured, it becomes the sole sampling decision maker (`samplingRate` iseffectively 100% so the sampler runs for every request).The sampler `type` maps to the standard [OTEL_TRACES_SAMPLER](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#general-sdk-configuration) environment variable:| `sampler.type` | Discriminated fields ||--------------------------------|-----------------------------------------|| `AlwaysOn` | — || `AlwaysOff` | — || `TraceIdRatio` | `samplingPercentage` (default 100%) || `ParentBasedAlwaysOn` | — || `ParentBasedAlwaysOff` | — || `ParentBasedTraceIdRatio` | `samplingPercentage` (default 100%) |The following configuration uses `ParentBasedTraceIdRatio` to respect the parent span's samplingdecision and drop all root spans:```yamlapiVersion:gateway.envoyproxy.io/v1alpha1kind:EnvoyProxymetadata:name:otelnamespace:envoy-gateway-systemspec:telemetry:tracing:provider:backendRefs:- name:otel-collectornamespace:monitoringport:4317type:OpenTelemetryopenTelemetry:sampler:type:ParentBasedTraceIdRatiosamplingPercentage:numerator:0
Custom Tags
You can add custom tags to the traces by setting the telemetry.tracing.tags in the EnvoyProxy CRD.
You can use the same format as Envoy’s access log command operators to define the tag values.
The following configurations show how to apply proxy with custom tags:
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyProxy
metadata:
name: otel
namespace: envoy-gateway-system
spec:
telemetry:
tracing:
# sample 100% of requests samplingRate: 100 provider:
backendRefs:
- name: otel-collector
namespace: monitoring
port: 4317 type: OpenTelemetry
tags:
# This is an example of using a literal as a tag value provider: "otel""k8s.pod.name": "%ENVIRONMENT(ENVOY_POD_NAME)%""k8s.namespace.name": "%ENVIRONMENT(ENVOY_POD_NAMESPACE)%"# This is an example of using a header value as a tag value"header1": "%REQUEST_HEADER(X-Header-1)%""requestedServerName": "%REQUESTED_SERVER_NAME%"
2.5.9 - RateLimit Observability
Envoy Gateway provides observability for the RateLimit instances.
This guide show you how to config RateLimit observability, includes traces.
Prerequisites
Install Envoy Gateway
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Install Add-ons
Envoy Gateway provides an add-ons Helm chart to simplify the installation of observability components. The documentation for the add-ons chart can be found
here.
Follow the instructions below to install the add-ons Helm chart.
Envoy Gateway’s RateLimit service exposes Prometheus metrics that help you answer:
Are requests being rate-limited?
Which domain/descriptor keys are hottest?
Are you getting close to limits (before you start denying traffic)?
Retrieve Prometheus metrics
Find the RateLimit Pod (names can vary by installation):
kubectl get pods -n envoy-gateway-system | grep -i ratelimit
Port-forward the metrics port (default is 19001):
exportRATELIMIT_POD="<paste a Pod name from the previous command>"kubectl -n envoy-gateway-system port-forward pod/${RATELIMIT_POD} 19001:19001
Verify the metrics exist and check the exact metric names:
curl -s localhost:19001/metrics | grep -E '^ratelimit_service_rate_limit_'| head
Tip: keep /metrics open while you write PromQL. It’s the fastest way to confirm whether a metric is exported as a counter (single series) or a histogram family (_bucket, _sum, _count).
Metric names and meanings
These metrics are exported per RateLimit domain and (by default) up to two descriptor-key labels:
ratelimit_service_rate_limit_total_hits Total number of requests evaluated by RateLimit (allowed + denied).
ratelimit_service_rate_limit_over_limit Number of requests that were denied (rate-limited).
ratelimit_service_rate_limit_near_limit Number of requests that were allowed, but close enough to the configured limit to be considered “near limit”.
(Useful as an early warning signal.)
ratelimit_service_rate_limit_within_limit Number of requests that were allowed and not considered “near limit”.
(Good for dashboards tracking allowed request QPS.)
ratelimit_service_rate_limit_shadow_mode Number of requests evaluated under shadow mode (dry-run / not enforced), when shadow mode is enabled in the rate limit service config.
Labels
Typical labels you’ll see:
domain: the RateLimit domain (a namespace for rate limit configs)
key1: first descriptor key (when present)
key2: second descriptor key (when present)
Note: The exported label depth is controlled by the StatsD → Prometheus mapping configuration. By default you should expect only domain, key1, and key2 to be labeled. Deeper descriptor segments typically won’t appear as additional labels unless the mapping is extended.
Warning: High Cardinality Risk
Descriptor keys can include unbounded values (e.g., client IPs, user IDs, unique headers). Grouping or filtering on those labels can create a time series per unique value and cause cardinality explosion in Prometheus. Avoid grouping by high-cardinality labels unless the value set is known and bounded.
PromQL examples
Histogram vs counter metric names
By default, Envoy Gateway’s StatsD → Prometheus mapping emits histogram-family metrics. If you customize the mapping, you may instead see counter-style metrics.
If you see *_count in /metrics, treat that as the primary “counter-like” series and use it with rate(). Use the counter-style examples only if the histogram family is not present.
After you apply RateLimit and send traffic, you should be able to see series for at least total_hits (and usually within_limit/over_limit) in /metrics.
If your PromQL query returns nothing:
Confirm the metric name in /metrics (do you have _count?).
Confirm label names in /metrics (do you have key1/key2?).
Confirm traffic is actually hitting RateLimit (look for total_hits moving).
Traces
By default, the Envoy Gateway does not configure RateLimit to send traces to the OpenTelemetry Sink.
You can configure the collector in the rateLimit.telemetry.tracing of the EnvoyGatewayCRD.
RateLimit uses the OpenTelemetry Exporter to export traces to the collector.
You can configure a collector that supports the OTLP protocol, which includes but is not limited to: OpenTelemetry Collector, Jaeger, Zipkin, and so on.
Note:
By default, the Envoy Gateway configures a 100% sampling rate for RateLimit, which may lead to performance issues.
Assuming the OpenTelemetry Collector is running in the observability namespace, and it has a service named otel-svc,
we only want to sample 50% of the trace data. We would configure it as follows:
After updating the ConfigMap, you will need to wait the configuration kicks in. You can force the configuration to be reloaded by restarting the envoy-gateway deployment.
Envoy Gateway provides support for exposing Envoy Gateway and Envoy Proxy metrics to a Prometheus instance.
This task shows you how to visualise the metrics exposed to Prometheus using Grafana.
Prerequisites
Install Envoy Gateway
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Install Add-ons
Envoy Gateway provides an add-ons Helm chart to simplify the installation of observability components. The documentation for the add-ons chart can be found
here.
Follow the instructions below to install the add-ons Helm chart.
Follow the steps from the Gateway Observability and Proxy Metrics to enable Prometheus metrics
for both Envoy Gateway (Control Plane) and Envoy Proxy (Data Plane).
Expose endpoints:
GRAFANA_IP=$(kubectl get svc grafana -n monitoring -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
Connecting Grafana with Prometheus datasource
To visualise metrics from Prometheus, we have to connect Grafana with Prometheus. If you installed Grafana follow the command
from prerequisites sections, the Prometheus datasource should be already configured.
You can also add the datasource manually by following the instructions from Grafana Docs.
Accessing Grafana
You can access the Grafana instance by visiting http://{GRAFANA_IP}, derived in prerequisites.
To log in to Grafana, use the credentials admin:admin.
Envoy Gateway has examples of dashboard for you to get started, you can check them out under Dashboards/envoy-gateway.
If you’d like import Grafana dashboards on your own, please refer to Grafana docs for importing dashboards.
Envoy Proxy Global
This dashboard example shows the overall downstream and upstream stats for each Envoy Proxy instance.
Envoy Clusters
This dashboard example shows the overall stats for each cluster from Envoy Proxy fleet.
Envoy Gateway Global
This dashboard example shows the overall stats exported by Envoy Gateway fleet.
Resources Monitor
This dashboard example shows the overall resources stats for both Envoy Gateway and Envoy Proxy fleet.
Update Dashboards
All dashboards of Envoy Gateway are maintained under charts/gateway-addons-helm/dashboards,
feel free to make contributions.
Grafonnet
Newer dashboards are generated with Jsonnet with the Grafonnet.
This is the preferred method for any new dashboards.
You can run make helm-generate.gateway-addons-helm to generate new version of dashboards.
All the generated dashboards have a .gen.json suffix.
Legacy Dashboards
Many of our older dashboards are manually created in the UI and exported as JSON and checked in.
These example dashboards cannot be updated in-place by default, if you are trying to
make some changes to the older dashboards, you can save them directly as a JSON file
and then re-import.
2.6 - Operations
This section includes Operations tasks.
2.6.1 - Customize EnvoyProxy
Envoy Gateway provides an EnvoyProxy CRD that can be linked to the ParametersRef
in a Gateway and GatewayClass, allowing cluster admins to customize the managed EnvoyProxy Deployment and
Service. To learn more about GatewayClass and ParametersRef, please refer to Gateway API documentation.
Note: We recommend creating a EnvoyProxy resource before creating a Gateway or GatewayClass that references it to avoid temporary disruption.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Before you start, you need to add Infrastructure.ParametersRef in Gateway, and refer to EnvoyProxy Config:
Note: MergeGateways cannot be set to true in your EnvoyProxy config if attaching to the Gateway.
You can also attach the EnvoyProxy resource to the GatewayClass using the parametersRef field.
This configuration is discouraged if you plan on creating multiple Gateways linking to the same
GatewayClass and would like different infrastructure configurations for each of them.
You can use egctl x translate
to get the default xDS Bootstrap configuration used by Envoy Gateway.
After applying the config, the bootstrap config will be overridden by the new config you provided.
Any errors in the configuration will be surfaced as status within the GatewayClass resource.
You can also validate this configuration using egctl x translate.
Customize EnvoyProxy Horizontal Pod Autoscaler
You can enable Horizontal Pod Autoscaler for EnvoyProxy Deployment. However, before enabling the HPA for EnvoyProxy, please ensure that the metrics-server component is installed in the cluster.
Once confirmed, you can apply it via EnvoyProxy Config as shown below:
After applying the config, the EnvoyProxy HPA (Horizontal Pod Autoscaler) is generated. However, upon activating the EnvoyProxy’s HPA, the Envoy Gateway will no longer reference the replicas field specified in the envoyDeployment, as outlined here. The replicas field is omitted from the generated Deployment entirely, so that Envoy Gateway does not take ownership of it and revert the replica count computed by the HPA. Use minReplicas to control the lower bound of the replica count instead.
Scale EnvoyProxy with an External Autoscaler
The built-in HPA only supports what a native
HorizontalPodAutoscaler metrics spec can express. To scale the proxy fleet with an autoscaler that Envoy Gateway
does not manage (a user-managed HorizontalPodAutoscaler, or a KEDAScaledObject scaling on a
Prometheus query or another event source), leave envoyDeployment.replicas unset.
Envoy Gateway only sets spec.replicas on the generated Deployment when you explicitly configure
envoyDeployment.replicas. When the field is unset it is omitted from the
server-side apply patch, so Envoy Gateway never takes ownership of it and will not revert the replica count computed by
your autoscaler on the next reconciliation. No additional Envoy Gateway configuration is required.
Migrating from an explicit replica count
If you previously set envoyDeployment.replicas and then remove it to hand the field to an external autoscaler,
server-side apply removes spec.replicas from the Deployment and the API server re-defaults it to 1. Expect a
scale-down until your autoscaler reconciles. Create the autoscaler before removing the field, or scale the Deployment
back up manually.
Targeting the generated Deployment
An external autoscaler needs a stable reference to the proxy Deployment. By default the name is autogenerated from the
owning Gateway, so use one of the following instead of recomputing it:
Pin the name: set envoyDeployment.name to a fixed value and use it as your autoscaler’s scaleTargetRef.name.
Select by label: the generated Deployment carries gateway.envoyproxy.io/owning-gateway-name and
gateway.envoyproxy.io/owning-gateway-namespace, or, when mergeGateways is enabled,
gateway.envoyproxy.io/owning-gatewayclass.
To confirm that Envoy Gateway is not managing the replica count, check that it is not listed as a field manager for
spec.replicas. The following command prints the managers of that field, and returns nothing when Envoy Gateway has
not claimed it:
You can customize the EnvoyProxy Command line options via spec.extraArgs in EnvoyProxy Config.
For example, the following configuration will add --disable-extensions arg in order to disable envoy.access_loggers/envoy.access_loggers.wasm extension:
After applying the configuration, you will see the custom-annotation: foobar has been added to the envoyproxy service.
Customize Filter Order
Under the hood, Envoy Gateway uses a series of Envoy HTTP filters
to process HTTP requests and responses, and to apply various policies.
By default, Envoy Gateway applies the following filters in the order shown:
envoy.filters.http.health_check
envoy.filters.http.fault
envoy.filters.http.cors
envoy.filters.http.csrf
envoy.filters.http.ext_authz
envoy.filters.http.api_key_auth
envoy.filters.http.basic_auth
envoy.filters.http.oauth2
envoy.filters.http.jwt_authn
envoy.filters.http.stateful_session
envoy.filters.http.buffer
envoy.filters.http.lua
envoy.filters.http.ext_proc
envoy.filters.http.wasm
envoy.filters.http.rbac
envoy.filters.http.local_ratelimit
envoy.filters.http.ratelimit
envoy.filters.http.grpc_web
envoy.filters.http.grpc_json_transcoder
envoy.filters.http.grpc_stats
envoy.filters.http.custom_response
envoy.filters.http.credential_injector
envoy.filters.http.compressor
envoy.filters.http.router
The default order in which these filters are applied is opinionated and may not suit all use cases.
To address this, Envoy Gateway allows you to adjust the execution order of these filters with the filterOrder field in the EnvoyProxy resource.
filterOrder is a list of customized filter order configurations. Each configuration can specify a filter
name and a filter to place it before or after. These configurations are applied in the order they are listed.
If a filter occurs in multiple configurations, the final order is the result of applying all these configurations in order.
To avoid conflicts, it is recommended to only specify one configuration per filter.
For example, the following configuration moves the envoy.filters.http.wasm filter before the envoy.filters.http.jwt_authn
filter and the envoy.filters.http.cors filter after the envoy.filters.http.basic_auth filter:
You can customize the IP family configuration for EnvoyProxy via the EnvoyProxy Config.
This allows the Envoy Proxy fleet to serve external clients over IPv4 as well as IPv6.
The below configuration sets the ipFamily to DualStack to allow ingressing IPv4 as well as IPv6 traffic.
Note: Envoy Gateway relies on the Service spec of the BackendRef resource (linked to xRoutes) to decide which type of IP addresses to use to route to them.
Save and apply the following resource to your cluster:
---apiVersion:gateway.envoyproxy.io/v1alpha1kind:EnvoyProxymetadata:name:custom-proxy-confignamespace:defaultspec:ipFamily: DualStack # Supports:IPv4, IPv6, DualStack, or PreferDualStack
After applying the config, the EnvoyProxy deployment will be configured to use the specified IP family. When set to DualStack, both IPv4 and IPv6 networking will be enabled.
Use PreferDualStack instead of DualStack to apply the same EnvoyProxy to both dual-stack and single-stack clusters. The proxy Service then gets both IP families where the cluster provides them, and the single available family otherwise.
Note: Your cluster must support the selected IP family configuration. For DualStack support, ensure your Kubernetes cluster is properly configured for dual-stack networking.
2.6.2 - Deploy Envoy Gateway in Air-Gapped Environments
Deploying the Envoy Gateway in an air-gapped environment using a Helm chart
requires careful configuration of the values.yaml file as well as adjustments
when deploying a Gateway resource.
You will need to specify custom image repositories for the following components
in the Helm chart. This can be done on a global level or image level.
It’s also possible to define the registry on a global level:
# Global settingsglobal:# If set, these take highest precedence and change both envoyGateway and ratelimit's container registry and pull secrets.# -- Global override for image registryimageRegistry:'custom-cr.internal.io'
Either the Gateway or GatewayClass must reference a custom EnvoyProxy resource
that explicitly specifies the location of the distroless Envoy container image.
Without this, the image will be pulled implicitly from Docker Hub.
For air-gapped deployments, you must configure the EnvoyProxy to use your internal container registry:
For comprehensive EnvoyProxy configuration options including deployment settings, resource limits, annotations, and other customizations, see Customize EnvoyProxy.
Default LoadBalancer Service Type
By default, Envoy uses a Service of type LoadBalancer. In air-gapped environments,
you may need to configure service annotations or change the service type depending
on your Kubernetes environment and network restrictions.
For detailed service configuration options including annotations, service types, and other networking customizations, see Customize EnvoyProxy.
2.6.3 - Deployment Mode
Deployment modes
One GatewayClass per Envoy Gateway Controller
An Envoy Gateway is associated with a single GatewayClass resource under one controller.
This is the simplest deployment mode and is suitable for scenarios where each Gateway needs to have its own dedicated set of resources and configurations.
Multiple GatewayClasses per Envoy Gateway Controller
An Envoy Gateway is associated with multiple GatewayClass resources under one controller.
Support for accepting multiple GatewayClasses was added here.
Separate Envoy Gateway Controllers
If you’ve instantiated multiple GatewayClasses, you can also run separate Envoy Gateway controllers in different namespaces, linking a GatewayClass to each of them for multi-tenancy.
Please follow the example Multi-tenancy.
Merged Gateways onto a single EnvoyProxy fleet
Recommendation
The mergeGateways feature was introduced before the Gateway API supported ListenerSet. For splitting listeners across multiple resources, prefer ListenerSet. See the ListenerSets guide for usage and a detailed comparison with merged Gateways.
By default, each Gateway has its own dedicated set of Envoy Proxy and its configurations.
However, for some deployments, it may be more convenient to merge listeners across multiple Gateways and deploy a single Envoy Proxy fleet.
This can help to efficiently utilize the infra resources in the cluster and manage them in a centralized manner, or have a single IP address for all of the listeners.
Setting the mergeGateways field in the EnvoyProxy resource linked to GatewayClass will result in merging all Gateway listeners under one GatewayClass resource.
The tuple of port, protocol, and hostname must be unique across all Listeners.
Gateway Namespace Mode is a deployment model for Envoy Gateway that creates Envoy Proxy infrastructure resources like Deployments, Services and ServiceAccounts in the namespace where each Gateway resource is defined, rather than in the Envoy Gateway controller namespace.
The default deployment model is - Envoy Gateway watches for resources such a Service & HTTPRoute in all namespaces
and creates managed data plane resources such as EnvoyProxy Deployment in the namespace where Envoy Gateway is running.
Envoy Gateway also supports Namespaced deployment mode, you can watch resources in the specific namespaces by assigning
EnvoyGateway.provider.kubernetes.watch.namespaces or EnvoyGateway.provider.kubernetes.watch.namespaceSelector and creates managed data plane resources in the namespace where Envoy Gateway is running.
The namespace where Envoy Gateway is running is always included so Envoy Gateway can reconcile its own managed infrastructure resources.
Multi-tenancy
Kubernetes
A tenant is a group within an organization (e.g. a team or department) who shares organizational resources. We recommend
each tenant deploy their own Envoy Gateway controller in their respective namespace. Below is an example of deploying Envoy Gateway
by the marketing and product teams in separate namespaces.
Lets deploy Envoy Gateway in the marketing namespace and also watch resources only in this namespace. We are also setting the controller name to a unique string here gateway.envoyproxy.io/marketing-gatewayclass-controller.
Lets create a GatewayClass linked to the marketing team’s Envoy Gateway controller, and as well other resources linked to it, so the backend application operated by this team can be exposed to external clients.
Lets create a GatewayClass linked to the product team’s Envoy Gateway controller, and as well other resources linked to it, so the backend application operated by this team can be exposed to external clients.
With the below command you can ensure that you are no able to access the marketing team’s backend exposed using the www.marketing.example.com hostname
and the product team’s data plane.
kubectl get gateways -n default
NAMESPACE NAME CLASS ADDRESS PROGRAMMED AGE
default merged-eg-1 merged-eg 172.18.255.202 True 2m4s
default merged-eg-2 merged-eg 172.18.255.202 True 2m4s
default merged-eg-3 merged-eg 172.18.255.202 True 2m4s
Verify that HTTPRoutes are deployed
kubectl get httproute -n default
NAMESPACE NAME HOSTNAMES AGE
default hostname1-route ["www.merged1.com"] 2m4s
default hostname2-route ["www.merged2.com"] 2m4s
default hostname3-route ["www.merged3.com"] 2m4s
If you take a look at the deployed Envoy Proxy service you would notice that all of the Gateway listeners ports are added to that service.
kubectl get service -n envoy-gateway-system
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
envoy-gateway ClusterIP 10.96.141.4 <none> 18000/TCP,18001/TCP 6m43s
envoy-gateway-metrics-service ClusterIP 10.96.113.191 <none> 19001/TCP 6m43s
envoy-merged-eg-668ac7ae LoadBalancer 10.96.48.255 172.18.255.202 8081:30467/TCP,8082:31793/TCP,8080:31153/TCP 3m17s
There should be also one deployment (envoy-merged-eg-668ac7ae-775f9865d-55zhs) for every Gateway and its name should reference the name of the GatewayClass.
kubectl get pods -n envoy-gateway-system
NAME READY STATUS RESTARTS AGE
envoy-gateway-5d998778f6-wr6m9 1/1 Running 0 6m43s
envoy-merged-eg-668ac7ae-775f9865d-55zhs 2/2 Running 0 3m17s
Testing the Configuration
Get the name of the merged gateways Envoy service:
exportENVOY_SERVICE=$(kubectl get svc -n envoy-gateway-system --selector=gateway.envoyproxy.io/owning-gatewayclass=merged-eg -o jsonpath='{.items[0].metadata.name}')
Fetch external IP of the service:
exportGATEWAY_HOST=$(kubectl get svc/${ENVOY_SERVICE} -n envoy-gateway-system -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
In certain environments, the load balancer may be exposed using a hostname, instead of an IP address. If so, replace
ip in the above command with hostname.
Curl the route hostname-route2 through Envoy proxy:
In standard deployment mode, Envoy Gateway creates all data plane resources in the controller namespace (typically envoy-gateway-system).
The motivation behind this was to operate with minimum permissions needed to be given for Envoy Gateway controller, as the control plane and data plane was deployed in the same namespace.
Gateway Namespace Mode changes this behavior by placing Envoy Proxy data plane resources like Deployments, Services and ServiceAccounts in each Gateway’s namespace, which provides stronger isolation and multi-tenancy compared to the Controller Namespace mode, as it isolates Envoy proxy data plane across different tenants.
This distributed architecture requires additional RBAC permissions for the Envoy Gateway controller to manage Kubernetes resources across multiple namespaces.
The default (Controller Namespace) deployment mode uses mTLS where both the client and server authenticate each other. However, in Gateway Namespace Mode, we’ve shifted to server-side TLS and JWT token validation between infra and control-plane.
Envoy proxy pods (running in Gateway namespaces) act as clients and authenticate using JWT tokens
Envoy Gateway controller pod (running in controller namespace) acts as the server and validates JWT tokens
Only the CA certificate is available in pods running in Gateway namespaces
Client certificates are not mounted in these namespaces
The Envoy proxy still validates server certificates using the CA certificate
Gateway Namespace Mode uses projected service account JWT tokens for authentication.
Use short-lived, audience-specific JWT tokens. These tokens are automatically mounted into pods via the projected volume mechanism
JWT validation ensures that only authorized proxies can connect to the xDS server
Note
Currently it is not supported to run Gateway Namespace Mode with Merged Gateways deployments.
Configuration
To enable Gateway Namespace Mode, configure the provider.kubernetes.deploy.type field in your Envoy Gateway Helm chart values:
When using Gateway Namespace Mode, Envoy Gateway needs additional RBAC permissions to create and manage resources across different namespaces. The following RBAC resources are automatically created when installing Envoy Gateway Helm Chart with Gateway Namespace Mode enabled.
Envoy Gateway also supports configuration to watch resources only in specific namespaces by using:
EnvoyGateway.provider.kubernetes.watch.namespaces - An explicit list of namespace names
EnvoyGateway.provider.kubernetes.watch.namespaceSelector - A label selector for dynamic namespace selection
The namespace where Envoy Gateway runs is always included in addition to the configured watched namespaces. Envoy Gateway uses this namespace for its own managed infrastructure resources, such as Envoy data plane Services and Deployments.
Using Explicit Namespace List
When you specify an explicit namespace list with Gateway Namespace Mode, Envoy Gateway will:
Watch for Gateway API resources in the specified namespaces
Also include the Envoy Gateway controller namespace for managed infrastructure resources
Create namespace-scoped Roles for infrastructure management in each specified namespace
Note: When using NamespaceSelector, the ClusterRole for infrastructure management is automatically created by the Helm chart, providing permissions across all namespaces that match the selector.
Testing
The following example demonstrates deploying two Gateways in different namespaces team-a and team-b.
Deploy resources on your cluster from the example, it will create two sets of backend deployments, Gateways and their respective HTTPRoutes in the previously created namespaces team-a and team-b.
kubectl get gateways -n team-a
NAME CLASS ADDRESS PROGRAMMED AGE
gateway-a eg 172.18.0.200 True 67s
kubectl get gateways -n team-b
NAME CLASS ADDRESS PROGRAMMED AGE
gateway-b eg 172.18.0.201 True 67s
Verify that HTTPRoutes are deployed
kubectl get httproute -n team-a
NAME HOSTNAMES AGE
team-a-route ["www.team-a.com"] 67s
kubectl get httproute -n team-b
NAME HOSTNAMES AGE
team-b-route ["www.team-b.com"] 67s
Envoy Proxy resources should be created now in the namespace of every Gateway.
kubectl get pods -n team-a
NAME READY STATUS RESTARTS AGE
envoy-team-a-gateway-a-b65c6264-d56f5d989-6dv5s 2/2 Running 0 65s
team-a-backend-6f786fb76f-nx26p 1/1 Running 0 65s
kubectl get pods -n team-b
NAME READY STATUS RESTARTS AGE
envoy-team-b-gateway-b-0ac91f5a-74f445884f-95pl8 2/2 Running 0 87s
team-b-backend-966b5f47c-zxngl 1/1 Running 0 87s
kubectl get services -n team-a
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
envoy-team-a-gateway-a-b65c6264 LoadBalancer 10.96.191.198 172.18.0.200 8080:30999/TCP 3m2s
team-a-backend ClusterIP 10.96.92.226 <none> 3000/TCP 3m2s
kubectl get services -n team-b
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
envoy-team-b-gateway-b-0ac91f5a LoadBalancer 10.96.144.13 172.18.0.201 8081:31683/TCP 3m43s
team-b-backend ClusterIP 10.96.26.162 <none> 3000/TCP 3m43s
Testing the Configuration
Fetch external IPs of the services:
exportGATEWAY_HOST_A=$(kubectl get gateway/gateway-a -n team-a -o jsonpath='{.status.addresses[0].value}')
exportGATEWAY_HOST_B=$(kubectl get gateway/gateway-b -n team-b -o jsonpath='{.status.addresses[0].value}')
Envoy Gateway enables zero-downtime deployments through graceful connection draining during pod termination.
Overview
The shutdown manager sidecar coordinates graceful connection draining during pod termination, providing:
Zero-downtime rolling updates
Configurable drain timeouts
Automatic health check failure to remove pods from load balancer rotation
Shutdown Process
Kubernetes sends SIGTERM to the pod’s containers and marks the pod as
terminating.
Shutdown manager starts Envoy listener drain via
/drain_listeners?graceful&skip_exit.
HTTP connections are drained according to drainStrategy. Envoy closes a
draining connection after its next response (Connection: close for
HTTP/1.1, GOAWAY for HTTP/2 and HTTP/3), and closes idle connections
before the drain window ends. Immediate drains every connection once the
drain starts, while Gradual spreads the draining across drainTimeout.
TCP and UDP proxy connections are not drained and stay open until Envoy
exits.
Envoy continues to accept and serve connections while listeners are draining.
Shutdown manager fails health checks via /healthcheck/fail, causing the
pod’s readiness probe to fail.
By default this happens immediately after listener drain starts.
When healthCheckFailureDelay is configured, this step is delayed without
delaying listener drain, connection monitoring, or the drain timeout.
With the Immediate strategy, failing health checks also drains all
connections immediately. With the Gradual strategy, it does not drain
connections by itself, so the gradual drain is preserved.
Connection monitoring begins, polling the active downstream connections and
UDP sessions.
Process exits when connections reach zero or drain timeout is exceeded
Configuration
Graceful shutdown behavior includes default values that can be overridden using the EnvoyProxy resource. The EnvoyProxy resource can be referenced in two ways:
Gateway-level: Referenced from a Gateway via infrastructure.parametersRef
GatewayClass-level: Referenced from a GatewayClass via parametersRef
Default Values:
drainTimeout: 60 seconds - Maximum time for connection draining
minDrainDuration: 10 seconds - Minimum wait before allowing exit
healthCheckFailureDelay: 0 seconds - Optional delay before failing health checks after drain starts
drainStrategy: Immediate - How HTTP connections are drained, either Immediate or Gradual
Changing drainStrategy on an existing Gateway changes the listener
configuration. The running Envoy proxies replace their listeners and drain their
existing connections at the same time, before the rolling update reaches them.
healthCheckFailureDelay does not extend the drain sequence or keep the pod’s
containers running. If the drain completes before healthCheckFailureDelay
elapses, /healthcheck/fail is not called. This can happen when connections
drop below exitAtConnections after minDrainDuration, or when
healthCheckFailureDelay is greater than or equal to drainTimeout.
When the Envoy proxy Deployment/DaemonSet is patched to run with hostNetwork: true, the envoy
container’s PreStop lifecycle hook (an HTTP GET to the shutdown-manager’s /shutdown/ready
endpoint) can fail with a kubelet error like failed to find networking container. This is
caused by a known kubelet bug
(kubernetes/kubernetes#134285): for
hostNetwork pods, kubelet cannot resolve an implicit target address for the PreStop httpGet
action because the pod IP reported by the CRI is empty.
Because the PreStop hook never completes, shutdown-manager doesn’t get a chance to drain
connections before Envoy exits, so in-flight connections can be dropped on pod termination.
As a workaround, you can patch the envoy container’s PreStop httpGet action to target
127.0.0.1 explicitly, which is reachable because the pod shares the node’s network namespace:
Only set host: 127.0.0.1 for hostNetwork pods. For the default (non-hostNetwork) case, kubelet
runs httpGet lifecycle hooks from the node’s network namespace, so hardcoding 127.0.0.1 would
target the node instead of the pod and break the hook.
2.6.6 - Overload Manager
Envoy Gateway configures the Envoy overload manager in the bootstrap of every managed Envoy proxy. The overload manager protects the proxy from running out of memory or file descriptors by shedding load before the process fails.
This page describes the defaults Envoy Gateway applies today. They are implementation defaults and may change in future releases. There is no dedicated EnvoyProxy field to configure them yet, see #3604.
These defaults are part of the default bootstrap. If you customize the bootstrap with spec.bootstrap in the EnvoyProxy resource, a Replace or JSONPatch bootstrap can change or remove the overload manager configuration. In that case, your bootstrap defines which limits apply.
Downstream connection limit
With the default bootstrap, Envoy Gateway configures the envoy.resource_monitors.global_downstream_max_connections resource monitor with a limit of 50000 active downstream connections, shared by all listeners of an Envoy proxy. Once the limit is reached, Envoy rejects new connections until existing ones close.
Heap memory limits
When the Envoy container has a memory limit, Envoy Gateway also configures the envoy.resource_monitors.fixed_heap resource monitor. Its maximum heap size is set to 80% of the container memory limit, which leaves headroom for memory that is not allocated on the heap.
The monitor reports heap pressure as the heap memory used by Envoy divided by that maximum heap size. Two overload actions are triggered by it:
Overload action
Heap pressure
Share of the container memory limit
Effect
envoy.overload_actions.shrink_heap
95%
76%
Envoy periodically releases free heap memory back to the operating system.
envoy.overload_actions.stop_accepting_requests
98%
78.4%
Envoy responds to every new HTTP request with a 503 and the body envoy overloaded. Requests already in progress and TCP or UDP traffic are not affected.
For example, with a memory limit of 1Gi, the maximum heap size is about 819Mi, and Envoy stops accepting requests when its heap usage reaches about 803Mi.
The heap usage measured by Envoy is lower than the memory usage of the container reported by Kubernetes, which also counts the Envoy binary, thread stacks and kernel memory charged to the container. Container memory metrics can therefore be above 78.4% of the limit before Envoy rejects requests.
If the Envoy container has no memory limit, which is the default, no heap monitor and no heap overload actions are configured. Only the downstream connection limit applies.
The listener that serves the readiness probe bypasses the overload manager, so an overloaded Envoy proxy keeps reporting ready while it rejects traffic. When Prometheus metrics are enabled, the listener that serves them bypasses the overload manager as well.
Autoscaling
If you autoscale the Envoy proxy on memory usage, as described in Customize EnvoyProxy Horizontal Pod Autoscaler, scale out before Envoy stops accepting requests. Use a ContainerResource metric for the envoy container. A Resource metric sums the memory of all containers in the pod, including the shutdown-manager container, so its threshold does not match the Envoy memory limit.
The HPA computes memory utilization against the memory request, and measures container memory, which is higher than the heap usage Envoy measures. The HPA uses the average utilization of all pods, so one pod can reach the limit before the average does. By default, the HPA scales out only when utilization is more than 10% above the target. Keep 1.1 × target utilization × memory request well below 78.4% of the memory limit, and leave room for the time new pods take to become ready.
For example, with a memory request and limit of 1Gi on the envoy container, a target utilization of 60% scales out when the average memory of the envoy containers is above about 676Mi, before Envoy stops accepting requests at about 803Mi of heap usage.
Alert on stop_accepting_requests.active to detect an Envoy proxy that is shedding load, and warn on a heap pressure above 90 to act before it does. If you restrict the exported statistics with telemetry.metrics.matches in the EnvoyProxy resource, include these statistics in the match list.
2.6.7 - Standalone Deployment Mode
Notice
Standalone mode is an experimental feature, please DO NOT use it in production.
Envoy Gateway also supports running in standalone mode. In this mode, Envoy Gateway
does not need to rely on Kubernetes and can be deployed directly on bare metal or virtual machines.
Currently, Envoy Gateway only supports the file provider and the host infrastructure provider combinations.
The file provider will configure the Envoy Gateway to get all gateway-api resources from file system.
The host infrastructure provider will configure the Envoy Gateway to deploy one Envoy Proxy as a host process.
Quick Start
Running locally on the host machine
In this quick-start, we will run Envoy Gateway in standalone mode with the file provider
and the host infrastructure provider.
Prerequisites
Create a local directory just for testing:
mkdir -p /tmp/envoy-gateway-test
You can download the Envoy Gateway binary from Github release,
or compile the binary on your own from project by using command:
make build
The compiled binary lies in {project-home}/bin/{os}/{arch}/envoy-gateway.
Create Certificates
All runners in Envoy Gateway are using TLS connection, so create these TLS certificates locally to
ensure the Envoy Gateway works properly.
envoy-gateway certgen --local
By default, certificates are stored in ~/.config/envoy-gateway/certs/. You can customize this
location using the --config-home flag (certs will be in a certs/ subdirectory):
Create a container network to run Envoy Gateway and a local server:
docker network create envoy-gateway-test
It’s important to widen permissions of a created directory to avoid Permission denied error
Create Certificates
All runners in Envoy Gateway are using TLS connection, so create these TLS certificates locally to
ensure the Envoy Gateway works properly.
docker run --rm --volume /tmp/envoy-gateway-test:/tmp/envoy-gateway envoyproxy/gateway:v0.0.0-latest certgen --local --config-home /tmp/envoy-gateway
Start Envoy Gateway
The following configuration should be placed into /tmp/envoy-gateway-test/standalone.yaml on the host:
apiVersion:gateway.envoyproxy.io/v1alpha1kind:EnvoyGatewaygateway:controllerName:gateway.envoyproxy.io/gatewayclass-controllerprovider:type:Customcustom:resource:type:Filefile:paths:["/tmp/envoy-gateway/config"]infrastructure:type:Hosthost:# Configure configHome and dataHome to use the mounted volume# configHome: for certificates# dataHome: for Envoy binariesconfigHome:/tmp/envoy-gatewaydataHome:/tmp/envoy-gatewaylogging:level:default:infoextensionApis:enableBackend:true
The --hostname field values is used in Backend object of Envoy Gateway as FQDN.
This way there is no need to update Backend object if IP address of container changed.
This subcommand allows users to show the summary of the status of specific or all resource types, in order to quickly find
out the status of any resources.
By default, egctl x status display all the conditions for one resource type. You can either add --quiet to only
display the latest condition, or add --verbose to display more details about current status.
Note
The resource types that this subcommand currently supports:
Some examples of this command after installing Multi-tenancy example manifest:
Show the summary of GatewayClass.
~ egctl x status gatewayclass
NAME TYPE STATUS REASON
eg-marketing Accepted True Accepted
eg-product Accepted True Accepted
Show the summary of all resource types under all namespaces, the resource type with empty status will be ignored.
~ egctl x status all -A
NAME TYPE STATUS REASON
gatewayclass/eg-marketing Accepted True Accepted
gatewayclass/eg-product Accepted True Accepted
NAMESPACE NAME TYPE STATUS REASON
marketing gateway/eg Programmed True Programmed
Accepted True Accepted
product gateway/eg Programmed True Programmed
Accepted True Accepted
NAMESPACE NAME PARENT TYPE STATUS REASON
marketing httproute/backend gateway/eg ResolvedRefs True ResolvedRefs
Accepted True Accepted
product httproute/backend gateway/eg ResolvedRefs True ResolvedRefs
Accepted True Accepted
Show the summary of all the Gateways with details under all namespaces.
~ egctl x status gateway --verbose --all-namespaces
NAMESPACE NAME TYPE STATUS REASON MESSAGE OBSERVED GENERATION LAST TRANSITION TIME
marketing eg Programmed True Programmed Address assigned to the Gateway, 1/1 envoy Deployment replicas available 1 2024-02-02 18:17:14 +0800 CST
Accepted True Accepted The Gateway has been scheduled by Envoy Gateway 1 2024-02-01 17:50:39 +0800 CST
product eg Programmed True Programmed Address assigned to the Gateway, 1/1 envoy Deployment replicas available 1 2024-02-02 18:17:14 +0800 CST
Accepted True Accepted The Gateway has been scheduled by Envoy Gateway 1 2024-02-01 17:52:42 +0800 CST
Show the summary of the latest Gateways condition under product namespace.
~ egctl x status gateway --quiet -n product
NAME TYPE STATUS REASON
eg Programmed True Programmed
Show the summary of latest HTTPRoutes condition under all namespaces.
~ egctl x status httproute --quiet --all-namespaces
NAMESPACE NAME PARENT TYPE STATUS REASON
marketing backend gateway/eg ResolvedRefs True ResolvedRefs
product backend gateway/eg ResolvedRefs True ResolvedRefs
egctl experimental dashboard
This subcommand streamlines the process for users to access the Envoy admin dashboard. By executing the following command:
egctl x dashboard envoy-proxy -n envoy-gateway-system envoy-engw-eg-a9c23fbb-558f94486c-82wh4
You will see the following output:
egctl x dashboard envoy-proxy -n envoy-gateway-system envoy-engw-eg-a9c23fbb-558f94486c-82wh4
http://localhost:19000
the Envoy admin dashboard will automatically open in your default web browser. This eliminates the need to manually locate and expose the admin port.
egctl experimental install
This subcommand can be used to install envoy-gateway.
egctl x install
By default, this will install both the envoy-gateway workload resource and the required gateway-api and envoy-gatewayCRDs.
We can specify to install only workload resources via --skip-crds
egctl x install --skip-crds
We can specify to install only CRDs resources via --only-crds
egctl x install --only-crds
We can specify --name and --namespace to install envoy-gateway in different places to support multi-tenant mode.
Note: If CRDs are already installed, then we need to specify --skip-crds to avoid repeated installation of CRDs resources.
egctl x install --name shop-backend --namespace shop
egctl experimental uninstall
This subcommand can be used to uninstall envoy-gateway.
egctl x uninstall
By default, this will only uninstall the envoy-gateway workload resource, if we want to also uninstall CRDs, we need to specify --with-crds
egctl x uninstall --with-crds
egctl experimental translate
This subcommand allows users to translate from an input configuration type to an output configuration type.
The translate subcommand can translate Kubernetes resources to:
Gateway API resources
This is useful in order to see how validation would occur if these resources were applied to Kubernetes.
Use the --to gateway-api parameter to translate to Gateway API resources.
Envoy Gateway intermediate representation (IR)
This represents Envoy Gateway’s translation of the Gateway API resources.
Use the --to ir parameter to translate to Envoy Gateway intermediate representation.
Envoy Proxy xDS
This is the xDS configuration provided to Envoy Proxy.
Use the --to xds parameter to translate to Envoy Proxy xDS.
In the below example, we will translate the Kubernetes resources (including the Gateway API resources) into xDS
resources.
You can also use the --type/-t flag to retrieve specific output types. In the below example, we will translate the Kubernetes resources (including the Gateway API resources) into xDS route resources.
You can see the output contains a EnvoyProxy resource that
can be used as a starting point to modify the xDS bootstrap resource for the managed Envoy Proxy fleet.
Envoy Gateway provides a built-in web-based admin console that offers a comprehensive interface for monitoring, debugging, and managing your Envoy Gateway deployment. The admin console provides real-time visibility into the control plane status, configuration state, performance metrics, and debugging capabilities.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
This command will automatically set up port forwarding and open the admin console in your default browser.
Configuration
The admin console can be configured through the EnvoyGateway configuration resource:
Development Configuration
For development environments, you may want to enable additional debugging features:
apiVersion:gateway.envoyproxy.io/v1alpha1kind:EnvoyGatewaymetadata:name:envoy-gateway-devnamespace:envoy-gateway-systemspec:admin:address:# Allow external access (use with caution)host:"0.0.0.0"port:19000# Enable pprof for performance debuggingenablePprof:true
Production Configuration
For production environments, use more restrictive settings:
apiVersion:gateway.envoyproxy.io/v1alpha1kind:EnvoyGatewaymetadata:name:envoy-gateway-prodnamespace:envoy-gateway-systemspec:admin:address:# Localhost only for securityhost:"127.0.0.1"port:19000# Disable pprof in productionenablePprof:false
Features
Dashboard
The main dashboard provides:
System Information: Version, uptime, and platform details
Component Status: Real-time status of all Envoy Gateway components
Quick Navigation: Easy access to all admin console features
Auto-refresh: Automatic updates every 30 seconds
Server Information
The server info page displays:
Component Health: Status of Provider Service, GatewayAPI Translator, xDS Translator, and Infrastructure Manager
Runtime Details: Version information, uptime, and system metrics
Configuration: Current EnvoyGateway configuration settings
Configuration Dump
The config dump feature provides:
Resource Explorer: Browse all Gateway API resources (Gateways, HTTPRoutes, etc.)
Search Functionality: Find resources by name or namespace
Real-time Updates: Live view of configuration changes
JSON Export: Download complete configuration as JSON
The search functionality allows you to quickly find specific resources:
You can also view the complete configuration dump in JSON format:
Statistics
The statistics page offers:
Prometheus Metrics: All control plane metrics in Prometheus format
Metrics Categories: Organized view of different metric types:
The metrics endpoint provides detailed Prometheus metrics:
Performance Profiling
When enablePprof is set to true, the profiling page provides:
CPU Profile: Analyze CPU usage patterns
Memory Heap: Monitor memory allocation and identify leaks
Goroutines: Debug concurrency issues and goroutine leaks
Mutex/Block: Find contention points in the application
Security Warning
Only enable pprof endpoints in development or debugging scenarios. These endpoints can expose sensitive information and should not be enabled in production environments.
3.2 - Advanced: Envoy Proxy Admin Interface
Overview
Platform admins looking to troubleshoot low level aspects of the data plane such as xDS config and heap dump, can directly connect to the Envoy Proxy Admin Interface.
Note: Application Developers may not have access to the namespace where the Envoy Proxy fleet is running and should rely on exported telemetry instead for troubleshooting.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The above command should succeed with status code 200.
Access
You will need to port-forward to the admin interface port (currently 19000) on the Envoy deployment that corresponds to a Gateway, since it only listens on the localhost
address for security reasons.
Get the name of the Envoy deployment. In this example its for Gateway eg in the default namespace:
exportENVOY_DEPLOYMENT=$(kubectl get deploy -n envoy-gateway-system --selector=gateway.envoyproxy.io/owning-gateway-namespace=default,gateway.envoyproxy.io/owning-gateway-name=eg -o jsonpath='{.items[0].metadata.name}')
After configuring and applying resources, you might find that Envoy Gateway does not behave as expected. This guide helps troubleshoot configuration issues.
Many syntax errors and simple semantic issues are caught during resource validation by the Kubernetes API Server, which rejects invalid resources. However, more complex configuration issues require additional debugging.
Prerequisites
Follow the steps below to install Envoy Gateway and the example manifest. Before
proceeding, you should be able to query the example backend using HTTP.
Expand for instructions
Install the Gateway API CRDs and Envoy Gateway using Helm:
Gateway API CRD compatibility
This command installs Gateway API CRDs. If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster,
use the provider-managed Gateway API CRD install steps
instead.
The status field in your resource definitions is your primary troubleshooting tool. It provides insights into whether a resource has been Accepted or not, along with the reason for rejection.
Using kubectl
This example below shows why an HTTPRoute has been Accepted but the ResolvedRefs condition is false because the backend does not exist.
Note: Almost all resources have a status field, so be sure to check them all.
The egctl CLI tool can quickly fetch the status of multiple resources at once:
egctl x status all -A
NAME TYPE STATUS REASON
gatewayclass/eg Accepted True Accepted
NAMESPACE NAME TYPE STATUS REASON
default gateway/eg Programmed True Programmed
Accepted True Accepted
NAMESPACE NAME TYPE STATUS REASON
default httproute/backend ResolvedRefs False BackendNotFound
Accepted True Accepted
For large-scale deployments, kube-state-metrics can help monitor the status of Envoy Gateway resources. For more details, refer to the Observability Guide.
Traffic
If a configuration is not accepted, Envoy Gateway assigns a direct_response to the affected route, causing clients to receive an HTTP 500 error.
this likely indicates a configuration issue. Review the relevant resource status for resolution steps.
3.4 - FAQ
Answers to recurring questions from GitHub issues and community discussions. If your question
isn’t covered here, check the rest of the Troubleshooting section or open a
GitHub issue.
Why does kubectl exec/port-forward fail when exposing kube-apiserver through Envoy Gateway?
You’ve routed the Kubernetes API server through Envoy Gateway, and plain calls work fine
(kubectl get, list, watch), but kubectl exec, attach, or port-forward fail with:
error: unable to upgrade connection: empty server response
The Envoy Gateway access log for the failing request shows a protocol error followed by a
rejected upgrade:
Root cause:exec, attach, and port-forward aren’t ordinary request/response calls — they
need a bidirectional streaming channel, which kubectl gets by asking the server to switch
protocols mid-connection (the SPDY/3.1 or websocket upgrade). Protocol upgrade is an
HTTP/1.1-only handshake (a 101 Switching Protocols response). If the connection between Envoy
Gateway and kube-apiserver negotiates HTTP/2 instead, that upgrade request has nowhere to go and
the request resets. get/list/watch don’t ask for an upgrade, so HTTP/2 handles them without
issue.
There are two ways to fix this:
Match the upstream protocol to the client’s, on the route (recommended)
Attach a BackendTrafficPolicy with useClientProtocol: true and an explicit httpUpgrade
list. Envoy then negotiates the upstream connection per-request to match what the client asked
for — ordinary calls still get HTTP/2, and upgrade requests get the HTTP/1.1 handshake they
need.
httpUpgrade must name every subprotocol you need passed through — kubectl has used both
spdy/3.1 (older versions) and websocket (current versions) across its history, so list both
unless you control every client’s kubectl version.
Use a TLSRoute instead of an HTTPRoute
Passing the connection through at L4 avoids terminating TLS (and negotiating HTTP/2) at the
gateway at all. This only works if kube-apiserver’s own certificate is valid for the hostname
your clients connect to — on a managed control plane, that certificate usually belongs to the
cloud provider and won’t match a custom domain.
Recommendation
Option 1 (useClientProtocol: true) is the best default: it’s scoped to a single route and keeps
HTTP/2 for every call that doesn’t need an upgrade. Reach for option 2 only if you control the
apiserver’s certificate.
Why does kubectl logs -f fail or get cut off after a while?
This is a separate issue with the same symptom family: a long-lived streaming response getting
cut off. HTTPRoute rules apply a default request timeout, which eventually terminates a
follow-mode log stream. Set an explicit, unbounded timeout on the route rule:
Why are requests with underscored header names rejected with HTTP 400 or a stream reset?
Clients that send headers with underscores in the name (for example X_Forwarded_For)
get HTTP/1 400 responses or HTTP/2 stream resets, even though you never configured a
ClientTrafficPolicy. This commonly surprises users migrating from nginx-ingress,
which accepts those headers by default.
See HeaderSettings for the other actions
(RejectRequest, DropHeader).
4 - Installation
This section includes installation related contents of Envoy Gateway.
4.1 - Install with Helm
Helm is a package manager for Kubernetes that automates the release and management of software on Kubernetes.
Envoy Gateway can be installed via a Helm chart with a few simple steps, depending on if you are deploying for the first time, upgrading Envoy Gateway from an existing installation, or migrating from Envoy Gateway.
Envoy Gateway is typically deployed in a Kubernetes cluster.
If you don’t have one yet, you can use kind to create a local cluster for testing purposes.
The default Helm install applies both Gateway API CRDs and Envoy Gateway CRDs. If your Kubernetes provider already
manages Gateway API CRDs for the cluster, confirm that the provider-installed Gateway API version and channel are
compatible with the Envoy Gateway release and the Gateway API resources you plan to use. If they are compatible,
install only the Envoy Gateway CRDs separately, then install the Envoy Gateway Helm chart with --set crds.enabled=false.
Note: quickstart.yaml defines that Envoy Gateway will listen for
traffic on port 80 on its globally-routable IP address, to make it easy to use
browsers to test Envoy Gateway. When Envoy Gateway sees that its Listener is
using a privileged port (<1024), it will map this internally to an
unprivileged port, so that Envoy Gateway doesn’t need additional privileges.
It’s important to be aware of this mapping, since you may need to take it into
consideration when debugging.
Gateway API CRDs (from the experimental channel): This channel includes additional alpha resources
such as TCPRoute and BackendTLSPolicy, which are commonly used by Envoy Gateway users.
Envoy Gateway CRDs: These are custom CRDs that extend the Gateway API to support additional
Envoy Gateway-specific features.
If you prefer to manage CRDs separately, the Envoy Gateway CRDs Helm Chart allows you
to install just the CRDs, with fine-grained control over:
Which Gateway API channel to use (standard or experimental)
Whether to include Envoy Gateway-specific CRDs
Use the following command to install the CRDs using helm template and kubectl
Note: We’re using helm template piped into kubectl apply instead of helm install due to a known Helm limitation
related to large CRDs in the templates/ directory.
Once the CRDs are installed, you can install the main Envoy Gateway Helm chart without re-applying CRDs by disabling the dependency via --set crds.enabled=false:
Clusters with compatible provider-managed Gateway API CRDs
Some Kubernetes providers can manage Gateway API CRDs for the cluster. For example, GKE can install Gateway API
Standard Channel CRDs when Gateway API is enabled for a cluster. Before relying on provider-managed CRDs, compare the
provider-installed Gateway API version and channel with the Envoy Gateway compatibility matrix
and the Gateway API resources required by your configuration.
You can check the installed Gateway API version and channel from the CRD annotations:
kubectl get crd gateways.gateway.networking.k8s.io \
-o go-template='version={{ index .metadata.annotations "gateway.networking.k8s.io/bundle-version" }} channel={{ index .metadata.annotations "gateway.networking.k8s.io/channel" }}{{ "\n" }}'
If the provider-managed Gateway API CRDs are compatible, leave the provider as the owner of those CRDs and install only
the Envoy Gateway CRDs:
Then install the main Envoy Gateway Helm chart without re-applying CRDs. Gateway API safe upgrade policy resources
(the safe-upgrades ValidatingAdmissionPolicy and binding shipped with the Gateway API bundle) are rendered from the
chart templates on install by default, so disable them when these resources are managed outside this chart:
If the provider-managed Gateway API CRDs are not compatible with your Envoy Gateway release or required Gateway API
resources, do not mix them with another copy installed by Envoy Gateway. Use a compatible Gateway API CRD installation
method for the cluster first, then install Envoy Gateway with --set crds.enabled=false.
Upgrading from the previous version
Helm does not update CRDs
that live in the /crds folder in the Helm Chart. So you will manually need to update the CRDs.
Follow the steps outlined in this section if you’re upgrading from a previous version.
Note: make sure to upgrade the CRDs first, then upgrade Envoy Gateway. Otherwise, Envoy Gateway may not find the new CRD versions and could fail to reconcile existing resources.
Gateway API v1.6 CRD upgrade required before Envoy Gateway upgrade
This release reconciles TCPRoute and UDPRoute via the gateway.networking.k8s.io/v1 API group (promoted in Gateway API v1.6).
You must upgrade the Gateway API CRDs to v1.6 before upgrading Envoy Gateway to avoid traffic disruption.
Standard channel users:v1alpha2 is no longer served in the Gateway API v1.6 standard channel.
You must update all TCPRoute and UDPRoute manifests to apiVersion: gateway.networking.k8s.io/v1
before upgrading the CRDs, or those routes will stop being served and traffic will be dropped.
Experimental channel users: both v1 and v1alpha2 are served after the CRD upgrade, so existing
v1alpha2 manifests continue to work without immediate changes. Updating manifests to v1 is still recommended.
If the v1.6 CRDs are not installed before Envoy Gateway is upgraded, TCP and UDP routes will be silently skipped until the CRDs are applied.
The stored version of TCPRoute and UDPRoute moves from v1alpha2 to v1. Plan a storage-version migration
before v1alpha2 is eventually removed:
kubectl get tcproutes.gateway.networking.k8s.io -A -o json | kubectl replace -f -
kubectl get udproutes.gateway.networking.k8s.io -A -o json | kubectl replace -f -
Helm chart customizations
Some of the quick ways of using the helm install command for envoy gateway installation are below.
Helm Chart Values
If you want to know all the available fields inside the values.yaml file, please see the Helm Chart Values.
Enable Backend API
The Backend API is not enabled by default. Enable it via Helm values:
Note: Above are some of the ways we can directly use for customization of our installation. But if you are looking for more complex changes values.yaml comes to rescue.
Here we have made three changes to our values.yaml file. Increase the resources limit for cpu to 700m, changed the port for grpc to 18005 and for ratelimit to 18006 and also updated the logging level to debug.
You can use the below command to install the envoy gateway using values.yaml file.
These are the ports used by Envoy Gateway and the managed Envoy Proxy.
Envoy Gateway
Envoy Gateway
Address
Port
Configurable
Xds EnvoyProxy Server
0.0.0.0
18000
No
Xds RateLimit Server
0.0.0.0
18001
No
Admin Server
127.0.0.1
19000
Yes
Metrics Server
0.0.0.0
19001
No
Health Check
127.0.0.1
8081
No
EnvoyProxy
Envoy Proxy
Address
Port
Admin Server
127.0.0.1
19000
Stats
0.0.0.0
19001
Shutdown Manager
0.0.0.0
19002
Readiness
0.0.0.0
19003
Next Steps
Envoy Gateway should now be successfully installed and running. To experience more abilities of Envoy Gateway, refer to Tasks.
4.2 - Install with Argo CD
Argo CD is a declarative, GitOps continuous delivery tool for Kubernetes.
Argo CD can be used to manage the deployment of Envoy Gateway on Kubernetes clusters.
Envoy Gateway is typically deployed in a Kubernetes cluster.
If you don’t have one yet, you can use kind to create a local cluster for testing purposes.
Argo CD must be installed in your Kubernetes cluster, and the argocd CLI must be available on your local machine.
If you haven’t set it up yet, you can follow the official installation guide to install Argo CD.
Install with Argo CD
Create a new Argo CD Application that pulls the Envoy Gateway Helm chart as its source.
Gateway API CRD compatibility
This Argo CD Application installs the Envoy Gateway Helm chart, which applies Gateway API CRDs by default.
If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster, use the
provider-managed Gateway API CRD guidance
to confirm compatibility and install only the Envoy Gateway CRDs separately, then configure this Application to skip CRD
installation by setting source.helm.skipCrds to true.
Set ServerSideApply to true to enable Kubernetes server-side apply. This helps avoid the 262,144-byte annotation size limit.
For simplicity, we apply the Application resource directly to the cluster.
In a production environment, it’s recommended to store this configuration in a Git repository and manage it using another Argo CD Application that uses Git as its source — following a GitOps workflow.
Note: quickstart.yaml defines that Envoy Gateway will listen for
traffic on port 80 on its globally-routable IP address, to make it easy to use
browsers to test Envoy Gateway. When Envoy Gateway sees that its Listener is
using a privileged port (<1024), it will map this internally to an
unprivileged port, so that Envoy Gateway doesn’t need additional privileges.
It’s important to be aware of this mapping, since you may need to take it into
consideration when debugging.
Helm chart customizations
You can customize the Envoy Gateway installation by using the Helm chart values.
Helm Chart Values
If you want to know all the available fields inside the values.yaml file, please see the Helm Chart Values.
Below is an example of how to customize the Envoy Gateway installation by using the valuesObject field in the Argo CD Application.
Argo CD supports multiple ways of specifying Helm chart values, you can find more details in the Argo CD documentation.
Open Ports
These are the ports used by Envoy Gateway and the managed Envoy Proxy.
Envoy Gateway
Envoy Gateway
Address
Port
Configurable
Xds EnvoyProxy Server
0.0.0.0
18000
No
Xds RateLimit Server
0.0.0.0
18001
No
Admin Server
127.0.0.1
19000
Yes
Metrics Server
0.0.0.0
19001
No
Health Check
127.0.0.1
8081
No
EnvoyProxy
Envoy Proxy
Address
Port
Admin Server
127.0.0.1
19000
Stats
0.0.0.0
19001
Shutdown Manager
0.0.0.0
19002
Readiness
0.0.0.0
19003
Next Steps
Envoy Gateway should now be successfully installed and running. To experience more abilities of Envoy Gateway, refer to Tasks.
4.3 - Install with Flux CD
Flux is a CNCF-graduated, GitOps-based continuous delivery tool for Kubernetes that reconciles cluster state from a Git repository or OCI registry.
Flux can be used to manage the deployment of Envoy Gateway on Kubernetes clusters.
Envoy Gateway is typically deployed in a Kubernetes cluster.
If you don’t have one yet, you can use kind to create a local cluster for testing purposes.
Flux must be installed in your Kubernetes cluster.
If you haven’t set it up yet, follow the Flux installation guide.
You can use the flux CLI, the Flux Operator, or any other supported method.
Install with Flux
The Envoy Gateway Helm chart is published as an OCI artifact at oci://docker.io/envoyproxy/gateway-helm.
Create an OCIRepository source and a HelmRelease that installs the chart into the envoy-gateway-system namespace.
Gateway API CRD compatibility
This Flux HelmRelease installs the Envoy Gateway Helm chart, which applies Gateway API CRDs by default.
If your Kubernetes provider already manages compatible Gateway API CRDs for the cluster, use the
provider-managed Gateway API CRD guidance
to confirm compatibility and install only the Envoy Gateway CRDs separately, then configure this HelmRelease to skip
CRD installation by setting spec.install.crds to Skip. You can also set spec.upgrade.crds to Skip to make the
upgrade behavior explicit.
Note: For simplicity, we apply these manifests directly to the cluster.
In a production environment, it’s recommended to store this configuration in a Git or OCI source that Flux reconciles, following a GitOps workflow.
Note: quickstart.yaml defines that Envoy Gateway will listen for
traffic on port 80 on its globally-routable IP address, to make it easy to use
browsers to test Envoy Gateway. When Envoy Gateway sees that its Listener is
using a privileged port (<1024), it will map this internally to an
unprivileged port, so that Envoy Gateway doesn’t need additional privileges.
It’s important to be aware of this mapping, since you may need to take it into
consideration when debugging.
Helm chart customizations
You can customize the Envoy Gateway installation by setting Helm chart values on the HelmRelease.
Helm Chart Values
If you want to know all the available fields inside the values.yaml file, please see the Helm Chart Values.
Below is an example of how to customize the Envoy Gateway installation by using the values field on the HelmRelease.
These are the ports used by Envoy Gateway and the managed Envoy Proxy.
Envoy Gateway
Envoy Gateway
Address
Port
Configurable
Xds EnvoyProxy Server
0.0.0.0
18000
No
Xds RateLimit Server
0.0.0.0
18001
No
Admin Server
127.0.0.1
19000
Yes
Metrics Server
0.0.0.0
19001
No
Health Check
127.0.0.1
8081
No
EnvoyProxy
Envoy Proxy
Address
Port
Admin Server
127.0.0.1
19000
Stats
0.0.0.0
19001
Shutdown Manager
0.0.0.0
19002
Readiness
0.0.0.0
19003
Next Steps
Envoy Gateway should now be successfully installed and running. To experience more abilities of Envoy Gateway, refer to Tasks.
4.4 - Install with Kubernetes YAML
This task walks you through installing Envoy Gateway in your Kubernetes cluster.
The manual installation process does not allow for as much configuration control (e.g. when you are using a custom domain Kubernetes cluster)
as the Helm install method, so if you need more control over your Envoy Gateway
installation, it is recommended that you use helm.
Envoy Gateway is typically deployed in a Kubernetes cluster.
If you don’t have one yet, you can use kind to create a local cluster for testing purposes.
The install.yaml manifest includes Gateway API CRDs and Envoy Gateway CRDs. If your Kubernetes provider already
manages compatible Gateway API CRDs for the cluster, do not use install.yaml; follow the
provider-managed Gateway API CRD Helm steps
instead. If the provider-managed Gateway API CRDs are not compatible with your Envoy Gateway release or required
Gateway API resources, use a compatible Gateway API CRD installation method before installing Envoy Gateway.
Envoy Gateway should now be successfully installed and running, but in order to experience more abilities of Envoy Gateway, you can refer to Tasks.
Upgrading from the previous version
Some manual migration steps are required to upgrade Envoy Gateway.
Gateway API v1.6 CRD upgrade required before Envoy Gateway upgrade
This release reconciles TCPRoute and UDPRoute via the gateway.networking.k8s.io/v1 API group (promoted in Gateway API v1.6).
You must upgrade the Gateway API CRDs to v1.6 before upgrading Envoy Gateway to avoid traffic disruption.
Standard channel users:v1alpha2 is no longer served in the Gateway API v1.6 standard channel.
You must update all TCPRoute and UDPRoute manifests to apiVersion: gateway.networking.k8s.io/v1
before upgrading the CRDs, or those routes will stop being served and traffic will be dropped.
Experimental channel users: both v1 and v1alpha2 are served after the CRD upgrade, so existing
v1alpha2 manifests continue to work without immediate changes. Updating manifests to v1 is still recommended.
If the v1.6 CRDs are not installed before Envoy Gateway is upgraded, TCP and UDP routes will be silently skipped until the CRDs are applied.
The stored version of TCPRoute and UDPRoute moves from v1alpha2 to v1. Plan a storage-version migration
before v1alpha2 is eventually removed:
kubectl get tcproutes.gateway.networking.k8s.io -A -o json | kubectl replace -f -
kubectl get udproutes.gateway.networking.k8s.io -A -o json | kubectl replace -f -
These are the ports used by Envoy Gateway and the managed Envoy Proxy.
Envoy Gateway
Envoy Gateway
Address
Port
Configurable
Xds EnvoyProxy Server
0.0.0.0
18000
No
Xds RateLimit Server
0.0.0.0
18001
No
Admin Server
127.0.0.1
19000
Yes
Metrics Server
0.0.0.0
19001
No
Health Check
127.0.0.1
8081
No
EnvoyProxy
Envoy Proxy
Address
Port
Admin Server
127.0.0.1
19000
Stats
0.0.0.0
19001
Shutdown Manager
0.0.0.0
19002
Readiness
0.0.0.0
19003
Next Steps
Envoy Gateway should now be successfully installed and running. To experience more abilities of Envoy Gateway, refer to Tasks.
4.5 - Install egctl
What is egctl?
egctl is a command line tool to provide additional functionality for Envoy Gateway users.
This task shows how to install the egctl CLI. egctl can be installed either from source, or from pre-built binary releases.
From The Envoy Gateway Project
The Envoy Gateway project provides two ways to fetch and install egctl. These are the official methods to get egctl releases. Installation through those methods can be found below the official methods.
Every release of egctl provides binary releases for a variety of OSes. These binary versions can be manually downloaded and installed.
Unpack it (tar -zxvf egctl_latest_linux_amd64.tar.gz)
Find the egctl binary in the unpacked directory, and move it to its desired destination (mv bin/linux/amd64/egctl /usr/local/bin/egctl)
From there, you should be able to run: egctl help.
egctl now has an installer script that will automatically grab the latest release version of egctl and install it locally.
You can fetch that script, and then execute it locally. It’s well documented so that you can read through it and understand what it is doing before you run it.
curl -fsSL -o get-egctl.sh https://gateway.envoyproxy.io/get-egctl.sh
chmod +x get-egctl.sh
# get help info of the bash get-egctl.sh --help
Yes, you can just use the below command if you want to live on the edge.
You can refer to the Use egctl task for more details about egctl.
4.6 - Control Plane Authentication Using Custom Certificates
Envoy Gateway establishes secure TLS connections for control plane communication between the Envoy Gateway deployment and the Envoy Proxy fleet. By default, the Helm chart generates the required certificates before Envoy Gateway starts.
This guide shows how to create and manage these certificates with cert-manager before installing Envoy Gateway.
The examples below use the default Kubernetes cluster domain, cluster.local. If your cluster uses a different domain, update both the kubernetesClusterDomain Helm value and the controller certificate DNS names.
Configure custom certificates for the control plane
Create the namespace where Envoy Gateway and the certificate resources will be installed.
kubectl create namespace envoy-gateway-system
Set up the CA issuer. This example uses a self-signed issuer to create the root CA.
Warning: Do not use the self-signed issuer in production. Use an issuer backed by a trusted certificate authority.
Verify the certificate resources and the expected TLS Secrets.
kubectl get certificates \
--namespace envoy-gateway-system
kubectl get secrets \
envoy-gateway \
envoy \
envoy-rate-limit \
--namespace envoy-gateway-system \
--output=custom-columns=NAME:.metadata.name,TYPE:.type
Create a Helm values file that specifies the Kubernetes cluster domain used in the controller certificate DNS names.
cat > custom-cert-values.yaml <<'EOF'
# Keep this value aligned with the cluster domain used in the
# envoy-gateway Certificate DNS names.
kubernetesClusterDomain: cluster.local
EOF
The certificate Secret names are fixed, so no certificate-specific Helm override is required. The chart uses the pre-created Secrets named envoy-gateway, envoy, and envoy-rate-limit.
Keep the certgen job enabled. It leaves existing certificate Secrets unchanged and creates any additional Secrets required by Envoy Gateway.
Install Envoy Gateway using the custom values file.
kubectl get deployment/envoy-gateway \
--namespace envoy-gateway-system
kubectl get pods \
--namespace envoy-gateway-system
helm status eg \
--namespace envoy-gateway-system
4.7 - Verify Image Signatures
The release workflow signs the Envoy Gateway image docker.io/envoyproxy/gateway with cosign keyless signing.
Keyless signing uses the GitHub Actions OIDC identity of the release workflow, so there is no private key to manage.
The signature is recorded in the Rekor public transparency log.
Only releases published after signing was added have a signature.
The command fails if the image has no valid signature from that workflow and tag.
The signature is on the multi-arch image index, so verify the tag or the index digest, not a per-platform digest.
"// Write your Alloy config here:\nlogging {\n level = \"info\"\n format = \"logfmt\"\n}\nloki.write \"alloy\" {\n endpoint {\n url = \"http://loki.monitoring.svc:3100/loki/api/v1/push\"\n }\n}\n// discovery.kubernetes allows you to find scrape targets from Kubernetes resources.\n// It watches cluster state and ensures targets are continually synced with what is currently running in your cluster.\ndiscovery.kubernetes \"pod\" {\n role = \"pod\"\n}\n\n// discovery.relabel rewrites the label set of the input targets by applying one or more relabeling rules.\n// If no rules are defined, then the input targets are exported as-is.\ndiscovery.relabel \"pod_logs\" {\n targets = discovery.kubernetes.pod.targets\n\n // Label creation - \"namespace\" field from \"__meta_kubernetes_namespace\"\n rule {\n source_labels = [\"__meta_kubernetes_namespace\"]\n action = \"replace\"\n target_label = \"namespace\"\n }\n\n // Label creation - \"pod\" field from \"__meta_kubernetes_pod_name\"\n rule {\n source_labels = [\"__meta_kubernetes_pod_name\"]\n action = \"replace\"\n target_label = \"pod\"\n }\n\n // Label creation - \"container\" field from \"__meta_kubernetes_pod_container_name\"\n rule {\n source_labels = [\"__meta_kubernetes_pod_container_name\"]\n action = \"replace\"\n target_label = \"container\"\n }\n\n // Label creation - \"app\" field from \"__meta_kubernetes_pod_label_app_kubernetes_io_name\"\n rule {\n source_labels = [\"__meta_kubernetes_pod_label_app_kubernetes_io_name\"]\n action = \"replace\"\n target_label = \"app\"\n }\n\n // Label creation - \"job\" field from \"__meta_kubernetes_namespace\" and \"__meta_kubernetes_pod_container_name\"\n // Concatenate values __meta_kubernetes_namespace/__meta_kubernetes_pod_container_name\n rule {\n source_labels = [\"__meta_kubernetes_namespace\", \"__meta_kubernetes_pod_container_name\"]\n action = \"replace\"\n target_label = \"job\"\n separator = \"/\"\n replacement = \"$1\"\n }\n\n // Label creation - \"container\" field from \"__meta_kubernetes_pod_uid\" and \"__meta_kubernetes_pod_container_name\"\n // Concatenate values __meta_kubernetes_pod_uid/__meta_kubernetes_pod_container_name.log\n rule {\n source_labels = [\"__meta_kubernetes_pod_uid\", \"__meta_kubernetes_pod_container_name\"]\n action = \"replace\"\n target_label = \"__path__\"\n separator = \"/\"\n replacement = \"/var/log/pods/*$1/*.log\"\n }\n\n // Label creation - \"container_runtime\" field from \"__meta_kubernetes_pod_container_id\"\n rule {\n source_labels = [\"__meta_kubernetes_pod_container_id\"]\n action = \"replace\"\n target_label = \"container_runtime\"\n regex = \"^(\\\\S+):\\\\/\\\\/.+$\"\n replacement = \"$1\"\n }\n}\n\n// loki.source.kubernetes tails logs from Kubernetes containers using the Kubernetes API.\nloki.source.kubernetes \"pod_logs\" {\n targets = discovery.relabel.pod_logs.output\n forward_to = [loki.process.pod_logs.receiver]\n}\n// loki.process receives log entries from other Loki components, applies one or more processing stages,\n// and forwards the results to the list of receivers in the component’s arguments.\nloki.process \"pod_logs\" {\n stage.static_labels {\n values = {\n cluster = \"envoy-gateway\",\n }\n }\n\n forward_to = [loki.write.alloy.receiver]\n}"
alloy.enabled
bool
false
alloy.fullnameOverride
string
"alloy"
dashboard.annotations
object
{}
dashboard.labels
object
{}
fluent-bit.config.filters
string
"[FILTER]\n Name kubernetes\n Match kube.*\n Merge_Log On\n Keep_Log Off\n K8S-Logging.Parser On\n K8S-Logging.Exclude On\n\n[FILTER]\n Name grep\n Match kube.*\n Regex $kubernetes['container_name'] ^envoy$\n\n[FILTER]\n Name parser\n Match kube.*\n Key_Name log\n Parser envoy\n Reserve_Data True\n"
fluent-bit.config.inputs
string
"[INPUT]\n Name tail\n Path /var/log/containers/*.log\n multiline.parser docker, cri\n Tag kube.*\n Mem_Buf_Limit 5MB\n Skip_Long_Lines On\n"
fluent-bit.config.outputs
string
"[OUTPUT]\n Name loki\n Match kube.*\n Host loki.monitoring.svc.cluster.local\n Port 3100\n Labels job=fluentbit, app=$kubernetes['labels']['app'], k8s_namespace_name=$kubernetes['namespace_name'], k8s_pod_name=$kubernetes['pod_name'], k8s_container_name=$kubernetes['container_name']\n"
Certgen is used to generate the certificates required by EnvoyGateway. If you want to construct a custom certificate, you can generate a custom certificate through Cert-Manager before installing EnvoyGateway. Certgen will not overwrite the custom certificate. Please do not manually modify values.yaml to disable certgen, it may cause EnvoyGateway OIDC,OAuth2,etc. to not work as expected.
Volume source for the Wasm module cache mounted at /var/lib/eg/wasm. Defaults to an emptyDir when left empty. Example: persist the Wasm module cache across controller restarts by backing it with a PersistentVolumeClaim: wasmCacheVolume: persistentVolumeClaim: claimName: envoy-gateway-wasm-cache
deployment.envoyGateway.wasmCacheVolume
object
{}
deployment.pod.affinity
object
{}
deployment.pod.annotations.“prometheus.io/port”
string
"19001"
deployment.pod.annotations.“prometheus.io/scrape”
string
"true"
deployment.pod.extraContainers
list
[]
Additional sidecar containers on the deployment definition.
deployment.pod.extraVolumeMounts
list
[]
deployment.pod.extraVolumes
list
[]
deployment.pod.initContainers
list
[]
Additional init containers on the deployment definition. Also used for native sidecars (an init container with restartPolicy: Always).
Extension managers keyed by name, rendered into config.envoyGateway.extensionManagers. Each entry takes the ExtensionManager fields (https://gateway.envoyproxy.io/docs/api/extension_types/#extensionmanager) except name, which comes from the key, plus order (non-negative integer sort key, default 0; ties sort by name) and enabled (default true; a bool, or a template string such as “{{ .Values.global.myExtension.enabled }}” that renders to true or false). Can’t be combined with config.envoyGateway.extensionManagers or config.envoyGateway.extensionManager.
global.imagePullSecrets
list
[]
Global override for image pull secrets
global.imageRegistry
string
""
Global override for image registry
global.images.envoyGateway.image
string
nil
Full image for the Envoy Gateway control plane Deployment installed by this chart.
global.images.envoyGateway.pullPolicy
string
nil
Image pull policy for the Envoy Gateway control plane Deployment. Default behavior: latest images will be Always else IfNotPresent.
global.images.envoyGateway.pullSecrets
list
[]
Pull secrets for the Envoy Gateway control plane Deployment.
global.images.envoyProxy.image
string
""
Full image for the managed Envoy Proxy data plane. This updates the generated envoyProxy config and does not change the envoy-gateway control plane Deployment image. If not specified, the default image built into envoy-gateway is used.
global.images.envoyProxy.pullPolicy
string
""
Image pull policy for the managed Envoy Proxy data plane. Default behavior: IfNotPresent.
global.images.envoyProxy.pullSecrets
list
[]
Pull secrets for the managed Envoy Proxy data plane.
global.images.ratelimit.image
string
"docker.io/envoyproxy/ratelimit:master"
global.images.ratelimit.pullPolicy
string
"IfNotPresent"
global.images.ratelimit.pullSecrets
list
[]
hpa.behavior
object
{}
hpa.enabled
bool
false
hpa.maxReplicas
int
1
hpa.metrics
list
[]
hpa.minReplicas
int
1
kubernetesClusterDomain
string
"cluster.local"
namespaceOverride
string
""
Override the namespace for resources deployed by the chart. Defaults to the release namespace.
podDisruptionBudget.minAvailable
int
0
rbac
object
{"create":true}
RBAC configuration. If disabled (rbac.create=false), no Roles, RoleBindings, ClusterRoles, or ClusterRoleBindings will be created by the chart. Warning: If disabled, you must manage and apply the required RBAC permissions externally, otherwise Envoy Gateway will lack permissions to watch resources and will not work as expected.
rbac.create
bool
true
Specifies whether RBAC resources should be created
service.annotations
object
{}
service.trafficDistribution
string
""
service.type
string
"ClusterIP"
Service type. Can be set to LoadBalancer with specific IP, e.g.: type: LoadBalancer loadBalancerIP: 10.236.90.20
topologyInjector.annotations
object
{}
topologyInjector.enabled
bool
true
4.11 - Migrating from Ingress Resources
Introduction
Migrating from Ingress to Envoy Gateway involves converting existing Ingress resources into resources compatible with Envoy Gateway. Two tools are available to help with this migration:
ingress2gateway
The official ingress2gateway tool (maintained by Kubernetes SIG-Network) transforms Ingress resources into Gateway API resources.
ingress2eg
The ingress2eg tool is an unofficial proof-of-concept forked from ingress2gateway with additional capabilities:
Envoy Gateway CRD Output: Generates not only Gateway API resources (Gateway, HTTPRoute) but also Envoy Gateway specific CRDs (BackendTrafficPolicy, SecurityPolicy, etc.)
We aim to get this feature merged upstream in ingress2gateway as well.
This guide will walk you through the prerequisites, installation of both tools, and provide example migration processes.
Prerequisites
Before you start the migration, ensure you have the following:
Envoy Gateway Installed: You need Envoy Gateway set up in your Kubernetes cluster. Follow the Envoy Gateway installation guide for details.
Kubernetes Cluster Access: Ensure you have access to your Kubernetes cluster and necessary permissions to manage resources.
Installation of ingress2gateway Tool: You need to install the ingress2gateway tool in your Kubernetes cluster and configure it accordingly. Follow the ingress2gateway tool installation guide for details.
Installation of ingress2eg Tool: You need to install the ingress2eg tool in your Kubernetes cluster and configure it accordingly. Follow the ingress2eg tool installation guide for details.
Example Migration
Here’s a step-by-step example of migrating from Ingress to Envoy Gateway using ingress2gateway:
To ensure the generated HTTPRoutes are programmed correctly in the Envoy Gateway data plane, create a GatewayClass that links to the Envoy Gateway controller.
Ensure the HTTPRoutes and Gateways are correctly set up and that traffic is being routed as expected. Validate the new configuration by checking the status of the Gateway and HTTPRoute resources.
kubectl get gateways
kubectl get httproutes
9. Monitor and Troubleshoot
Monitor the Envoy Gateway logs and metrics to ensure everything is functioning correctly. Troubleshoot any issues by reviewing the Gateway and HTTPRoute statuses and Envoy Gateway controller logs.
Example Migration using ingress2eg
The ingress2eg tool provides extended support for NGINX-specific annotations and generates Envoy Gateway CRD resources in addition to Gateway API resources. Follow steps 1-2 from the ingress2gateway example above for Envoy Gateway installation and GatewayClass creation.
1. Install ingress2eg
Ensure you have the ingress2eg tool installed. Follow the installation guide for details.
2. Prepare Ingress with NGINX Annotations
Here’s an example Ingress resource using NGINX annotations for rate limiting and CORS:
apiVersion:networking.k8s.io/v1kind:Ingressmetadata:name:example-ingress-nginxnamespace:defaultannotations:nginx.ingress.kubernetes.io/limit-rps:"10"nginx.ingress.kubernetes.io/enable-cors:"true"nginx.ingress.kubernetes.io/cors-allow-methods:"GET, POST, OPTIONS"nginx.ingress.kubernetes.io/cors-allow-origin:"https://example.com"spec:rules:- host:example.comhttp:paths:- path:/apipathType:Prefixbackend:service:name:api-serviceport:number:80
3. Run ingress2eg
Use ingress2eg to convert the Ingress resources. The tool supports various options:
# Convert from cluster resources in a specific namespaceingress2eg print --namespace default
# Convert from a fileingress2eg print --input-file ingress.yaml
4. Review Generated Resources
For the above Ingress example, ingress2eg generates the following resources:
Gateway API Resources:
Gateway
HTTPRoute
Envoy Gateway CRD Resources:
BackendTrafficPolicy: Generated from rate limiting annotation (limit-rps)
SecurityPolicy: Generated from CORS annotations (enable-cors, cors-allow-methods, cors-allow-origin)
Generated BackendTrafficPolicy (from the limit-rps annotation):
By following this guide, users can effectively migrate their existing Ingress resources to Envoy Gateway using the Ingress2gateway, Ingress2eg package. Creating a GatewayClass and linking it to the Envoy Gateway controller ensures that the translated resources are properly programmed in the data plane, providing a seamless transition to the Envoy Gateway environment.
5 - API References
This section includes API References.
5.1 - Gateway API Extensions
Envoy Gateway provides these extensions to support additional features not available in the Gateway API today
HTTPProtocolVersion1_0 specifies that HTTP/1.0 should be negotiable with ALPN
http/1.1
HTTPProtocolVersion1_1 specifies that HTTP/1.1 should be negotiable with ALPN
h2
HTTPProtocolVersion2 specifies that HTTP/2 should be negotiable with ALPN
ALSEnvoyProxyAccessLog
ALSEnvoyProxyAccessLog defines the gRPC Access Log Service (ALS) sink.
The service must implement the Envoy gRPC Access Log Service streaming API:
https://www.envoyproxy.io/docs/envoy/latest/api-v3/service/accesslog/v3/als.proto
Access log format information is passed in the form of gRPC metadata when the
stream is established.
BackendRef references a Kubernetes object that represents the backend server to which the authorization request will be sent. Deprecated: Use BackendRefs instead. This field will be removed in v1.11.
BackendSettings holds configuration for managing the connection to the backend.
logName
string
false
LogName defines the friendly name of the access log to be returned in StreamAccessLogsMessage.Identifier. This allows the access log server to differentiate between different access logs coming from the same Envoy.
CredentialRefs is the Kubernetes secret which contains the API keys. This is an Opaque secret. Each API key is stored in the key representing the client id. If the secrets have a key for a duplicated client, the first one will be used.
ExtractFrom is where to fetch the key from the coming request. The value from the first source that has a key will be used.
forwardClientIDHeader
string
false
ForwardClientIDHeader is the name of the header to forward the client identity to the backend service. The header will be added to the request with the client id as the value.
sanitize
boolean
false
Sanitize indicates whether to remove the API key from the request before forwarding it to the backend service.
ActiveHealthCheck
ActiveHealthCheck defines the active health check configuration.
EG supports various types of active health checking including HTTP, TCP.
InitialJitter defines the maximum time Envoy will wait before the first health check. Envoy will randomly select a value between 0 and the initial jitter value.
unhealthyThreshold
integer
false
3
UnhealthyThreshold defines the number of unhealthy health checks required before a backend host is marked unhealthy. Without RetriableStatuses configured, any health check failure results in the host being immediately considered unhealthy. When RetriableStatuses is set, health checks returning those statuses are retried up to this threshold before the host is marked unhealthy.
healthyThreshold
integer
false
1
HealthyThreshold defines the number of healthy health checks required before a backend host is marked healthy.
disableConnectionReuse
boolean
false
DisableConnectionReuse determines whether the active health check connection to a backend host is closed after each health check probe. When set to true, Envoy opens a new connection for each health check, which is useful for backends (such as haproxy-style agent checks) that do not expect a reused connection. Defaults to false, which reuses the connection across probes.
Overrides defines the configuration of the overriding health check settings for all endpoints in the backend cluster. This allows customization of port and other settings that may differ from the main service configuration.
HealthCheckLog defines health check event logging configuration for this cluster. When set, HC probe outcomes are logged to the configured sinks. Takes precedence over the gateway-level EnvoyProxy.spec.telemetry.healthCheckLog.
ActiveHealthCheckPayload
ActiveHealthCheckPayload defines the encoding of the payload bytes in the payload.
ActiveHealthCheckerTypeHTTP defines the HTTP type of health checking.
TCP
ActiveHealthCheckerTypeTCP defines the TCP type of health checking.
GRPC
ActiveHealthCheckerTypeGRPC defines the GRPC type of health checking.
AdmissionControl
AdmissionControl configures health-based load shedding for upstream backends.
Envoy tracks recent upstream responses over a sliding sampling window. When the
observed success rate drops below the configured threshold, Envoy
probabilistically rejects new requests before forwarding them upstream. This can
reduce pressure on degraded backends and give them time to recover.
All fields are optional. When omitted, Envoy’s admission control defaults are used.
SamplingWindow defines the time window over which request success rates are calculated. Must be at least 1s; Envoy truncates the window to whole seconds and uses it as the denominator in RPS calculations, so sub-second values would produce a zero denominator. Defaults to 30s if not specified.
minSuccessRate
integer
false
MinSuccessRate is the lowest request success rate, as a percentage in the range [1, 100], at which the filter will not reject requests. Defaults to 95 if not specified. Envoy rejects values below 1%, so values lower than 1 are not allowed.
rejectionAggression
integer
false
RejectionAggression controls how steeply the rejection probability rises as the observed success rate falls below MinSuccessRate. A value of 1 produces a linear curve; higher values reject more aggressively for a given drop in success rate. Must be greater than 0; values below 1 are clamped to 1. Defaults to 1.
minRequestRate
integer
false
MinRequestRate defines the minimum requests per second below which requests will pass through the filter without rejection. Defaults to 0 if not specified.
maxRejectionPercent
integer
false
MaxRejectionPercent represents the upper limit of the rejection probability, expressed as a percentage in the range [0, 100]. Defaults to 80 if not specified.
Rules defines a list of authorization rules. These rules are evaluated in order, the first matching rule will be applied, and the rest will be skipped. For example, if there are two rules: the first rule allows the request and the second rule denies it, when a request matches both rules, it will be allowed.
Name of the HTTP header. The header name is case-insensitive unless PreserveHeaderCase is set to true. For example, “Foo” and “foo” are considered the same header.
values
string array
true
Values are the values that the header must match. If multiple values are specified, the rule will match if any of the values match.
AuthorizationRule
AuthorizationRule defines a single authorization rule.
Name is a user-friendly name for the rule. If not specified, Envoy Gateway will generate a unique name for the rule. The name is reported as the matched policy in access logs and RBAC metadata, so it should be unique within the policy. “default” is reported when no rule matches.
Principal specifies the client identity of a request. If there are multiple principal types, all principals must match for the rule to match. For example, if there are two principals: one for client IP and one for JWT claim, the rule will match only if both the client IP and the JWT claim match.
CEL specifies a Common Expression Language expression to evaluate for the request. If specified, the expression must evaluate to true for the rule to match. The expression can use Envoy attributes exposed to the CEL runtime. Request attributes, such as request.path, request.url_path, request.host, request.scheme, request.method, request.headers, and request.query, are generally available during authorization. Connection attributes, such as source.address, source.port, destination.address, destination.port, connection.mtls, and connection.requested_server_name, may also be used. Dynamic metadata and filter state produced by earlier filters may also be available through attributes such as metadata and filter_state. Response attributes are only available after the request completes and should not be used for authorization decisions. For more details, see: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/attributes The rule matches only when the expression evaluates to a boolean true. Non-boolean results, false, null, and CEL evaluation errors are treated as no match. Examples: request.headers['x-tenant'] == 'team-a' request.method == 'POST' && request.path.startsWith('/admin')
MaxInterval is the maximum interval between retries. This parameter is optional, but must be greater than or equal to the base_interval if set. The default is 10 times the base_interval
Backend
Backend allows the user to configure the endpoints of a backend and
the behavior of the connection from Envoy Proxy to the backend.
BackendCluster contains all the configuration required for configuring access
to a backend. This can include multiple endpoints, and settings that apply for
managing the connection to all these endpoints.
BackendRef references a Kubernetes object that represents the backend server to which the authorization request will be sent. Deprecated: Use BackendRefs instead. This field will be removed in v1.11.
BufferLimit Soft limit on size of the cluster’s connections read and write buffers. BufferLimit applies to connection streaming (maybe non-streaming) channel between processes, it’s in user space. If unspecified, an implementation defined default is applied (32768 bytes). For example, 20Mi, 1Gi, 256Ki etc. Note: that when the suffix is not provided, the value is interpreted as bytes.
Preconnect configures proactive upstream connections to reduce latency by establishing connections before they’re needed and avoiding connection establishment overhead. If unset, Envoy will fetch connections as needed to serve in-flight requests.
Zone defines the service zone of the backend endpoint.
BackendHTTP1Settings
BackendHTTP1Settings provides HTTP/1 configuration for backend connections.
Setting this field to an empty value (http1: {}), or configuring any of its members,
forces explicit HTTP/1 for backend connections.
BackendHTTP3ModeAuto uses HTTP/3 only for backends that advertise support for it through an alt-svc response header. Envoy races a QUIC connection against a TCP one and uses whichever is established first, so it falls back to HTTP/1.1 or HTTP/2 when QUIC is unavailable.
Always
BackendHTTP3ModeAlways always uses HTTP/3, without falling back to TCP. Use this only in environments where the backend is known to speak HTTP/3. Active health checks are still sent over TLS on TCP, so a backend with an active health check must also accept TCP on the same port.
BackendHTTP3Settings
BackendHTTP3Settings provides HTTP/3 configuration for backend connections.
RouteStatName defines the value of the Route stat_prefix, determining how the route stats are named. For more details, see envoy docs: https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/route/v3/route_components.proto#config-route-v3-route The supported operators for this pattern are: %ROUTE_NAME%: name of Gateway API xRoute resource %ROUTE_NAMESPACE%: namespace of Gateway API xRoute resource %ROUTE_KIND%: kind of Gateway API xRoute resource Example: %ROUTE_KIND%/%ROUTE_NAMESPACE%/%ROUTE_NAME% => httproute/my-ns/my-route Disabled by default.
BackendRef
BackendRef defines how an ObjectReference that is specific to BackendRef.
Kind is the Kubernetes resource kind of the referent. For example “Service”. Defaults to “Service” when not specified. ExternalName services can refer to CNAME DNS records that may live outside of the cluster and as such are difficult to reason about in terms of conformance. They also may not be safe to forward to (see CVE-2021-25740 for more information). Implementations SHOULD NOT support ExternalName Services. Support: Core (Services with a type other than ExternalName) Support: Implementation-specific (Services with type ExternalName)
Namespace is the namespace of the backend. When unspecified, the local namespace is inferred. Note that when a namespace different than the local namespace is specified, a ReferenceGrant object is required in the referent namespace to allow that namespace’s owner to accept the reference. See the ReferenceGrant documentation for details. Support: Core
Port specifies the destination port number to use for this resource. Port is required when the referent is a Kubernetes Service. In this case, the port number is the service port number, not the target port. For other resources, destination port might be derived from the referent resource or this field.
weight
integer
false
1
Weight specifies the proportion of requests forwarded to the referenced backend. This is computed as weight/(sum of all weights in this BackendRefs list). For non-zero values, there may be some epsilon from the exact proportion defined here depending on the precision an implementation supports. Weight is not a percentage and the sum of weights does not need to equal 100. If only one backend is specified and it has a weight greater than 0, 100% of the traffic is forwarded to that backend. If weight is set to 0, no traffic should be forwarded for this entry. If unspecified, weight defaults to 1. Support for this field varies based on the context where used.
fallback
boolean
false
Fallback indicates whether the backend is designated as a fallback. Multiple fallback backends can be configured. It is highly recommended to configure active or passive health checks to ensure that failover can be detected when the active backends become unhealthy and to automatically readjust once the primary backends are healthy again. The overprovisioning factor is set to 1.4, meaning the fallback backends will only start receiving traffic when the health of the active backends falls below 72%.
BackendSettings
BackendSettings provides the various knobs that can be set to control how traffic to a given
backend will be configured. It embeds ClusterSettings (CDS-only fields) and adds
route-level fields like Retry.
HTTP3 enables HTTP/3 for backend connections. HTTP/3 always runs over TLS, so the backend must be configured with TLS through a BackendTLSPolicy or the Backend’s spec.tls. HTTP/3 is only supported for the backends of a route, through BackendTrafficPolicy. It is rejected for the backends of other resources, such as the external services of a SecurityPolicy or EnvoyExtensionPolicy and the sinks of an EnvoyProxy.
HTTP1 provides HTTP/1 configuration for backend connections. When both this field and the deprecated HTTP1 field on ClientTrafficPolicy are set, this field takes precedence for backend (upstream) traffic. Behavior when targeting route kinds that do not use HTTP/1: - GRPCRoute, TCPRoute, TLSRoute, UDPRoute: targeting these route kinds directly adds a Warning condition on the policy; the field is ignored. - Gateway / ListenerSet / sectionName targets: this field is silently ignored for any GRPCRoute, TCPRoute, TLSRoute, or UDPRoute destinations beneath that target; no warning is emitted. - gRPC-only external services (ExtProc, gRPC ExtAuth, ALS, OpenTelemetry access log/metrics, tracing providers): rejected at admission on their own BackendSettings via separate validation rules.
Retry provides more advanced usage, allowing users to customize the number of retries, retry fallback strategy, and retry triggering conditions. If not set, retry will be disabled.
BackendSpec
BackendSpec describes the desired state of BackendSpec.
KubernetesService defines the Kubernetes Service to be used when connecting to the backend. It must be set when Type is KubernetesService, and must not be set otherwise. The endpoints of the Service are discovered from its EndpointSlices, exactly as they are for a Service backendRef, so the resulting cluster keeps pod-level load balancing, health checking, session persistence, endpoint draining and zone awareness.
AppProtocols defines the application protocols to be supported when connecting to the backend. For a KubernetesService backend, this takes precedence over the appProtocol of the Service port.
fallback
boolean
false
Fallback indicates whether the backend is designated as a fallback. It is highly recommended to configure active or passive health checks to ensure that failover can be detected when the active backends become unhealthy and to automatically readjust once the primary backends are healthy again. The overprovisioning factor is set to 1.4, meaning the fallback backends will only start receiving traffic when the health of the active backends falls below 72%.
TLS defines the TLS settings for the backend. If TLS is specified here and a BackendTLSPolicy is also configured for the backend, the final TLS settings will be a merge of both configurations. In case of overlapping fields, the values defined in the BackendTLSPolicy will take precedence.
ClientCertificateRef defines the reference to a Kubernetes Secret that contains the client certificate and private key for Envoy to use when connecting to backend services and external services, such as ExtAuth, ALS, OpenTelemetry, etc. The Secret must be in the same namespace as the EnvoyProxy or Backend resource that references it. Cross-namespace references are not supported, even with a ReferenceGrant. The ReferenceGrant requirement in the namespace field’s description is inherited from the Gateway API SecretObjectReference type and does not apply to this field.
Max specifies the maximal TLS protocol version to allow The default is TLS 1.3 if this is not specified.
ciphers
string array
false
Ciphers specifies the set of cipher suites supported when negotiating TLS 1.0 - 1.2. This setting has no effect for TLS 1.3. For Envoy TLS cipher suite configuration semantics and default cipher lists, see the Envoy documentation: https://www.envoyproxy.io/docs/envoy/latest/api-v3/extensions/transport_sockets/tls/v3/common.proto#extensions-transport-sockets-tls-v3-tlsparameters Supported cipher suite names: - ECDHE-ECDSA-AES128-GCM-SHA256 - ECDHE-RSA-AES128-GCM-SHA256 - ECDHE-ECDSA-AES256-GCM-SHA384 - ECDHE-RSA-AES256-GCM-SHA384 - ECDHE-ECDSA-CHACHA20-POLY1305 - ECDHE-RSA-CHACHA20-POLY1305 - ECDHE-ECDSA-AES128-SHA - ECDHE-RSA-AES128-SHA - AES128-GCM-SHA256 - AES128-SHA - ECDHE-ECDSA-AES256-SHA - ECDHE-RSA-AES256-SHA - AES256-GCM-SHA384 - AES256-SHA Supported IANA/RFC aliases: - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 - TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 - TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 - TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA - TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA - TLS_RSA_WITH_AES_128_GCM_SHA256 - TLS_RSA_WITH_AES_128_CBC_SHA - TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA - TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA - TLS_RSA_WITH_AES_256_GCM_SHA384 - TLS_RSA_WITH_AES_256_CBC_SHA In non-FIPS Envoy Proxy builds the default cipher list is: - [ECDHE-ECDSA-AES128-GCM-SHA256|ECDHE-ECDSA-CHACHA20-POLY1305] - [ECDHE-RSA-AES128-GCM-SHA256|ECDHE-RSA-CHACHA20-POLY1305] - ECDHE-ECDSA-AES256-GCM-SHA384 - ECDHE-RSA-AES256-GCM-SHA384 In builds using BoringSSL FIPS the default cipher list is: - ECDHE-ECDSA-AES128-GCM-SHA256 - ECDHE-RSA-AES128-GCM-SHA256 - ECDHE-ECDSA-AES256-GCM-SHA384 - ECDHE-RSA-AES256-GCM-SHA384
ecdhCurves
string array
false
ECDHCurves specifies the set of supported ECDH curves. In non-FIPS Envoy Proxy builds the default curves are: - X25519 - P-256 In builds using BoringSSL FIPS the default curve is: - P-256
signatureAlgorithms
string array
false
SignatureAlgorithms specifies which signature algorithms the listener should support.
ALPNProtocols supplies the list of ALPN protocols that should be exposed by the listener or used by the proxy to connect to the backend. Defaults: 1. HTTPS Routes: h2 and http/1.1 are enabled in listener context. 2. Other Routes: ALPN is disabled. 3. Backends: proxy uses the appropriate ALPN options for the backend protocol. When an empty list is provided, the ALPN TLS extension is disabled. Defaults to [h2, http/1.1] if not specified. Typical Supported values are: - http/1.0 - http/1.1 - h2
Fingerprints specifies TLS client fingerprinting. When specified, a JAX fingerprint derived from the client’s TLS handshake is generated. The fingerprint can be logged in access logs or forwarded to upstream services using request headers. Fingerprinting is disabled if not specified. Supported values are: - JA3 - JA4
BackendTLSSettings
BackendTLSSettings holds the TLS settings for the backend.
CACertificateRefs contains one or more references to Kubernetes objects that contain TLS certificates of the Certificate Authorities that can be used as a trust anchor to validate the certificates presented by the backend. A single reference to a Kubernetes ConfigMap or a Kubernetes Secret, with the CA certificate in a key named ca.crt is currently supported. If CACertificateRefs is empty or unspecified, then WellKnownCACertificates must be specified. Only one of CACertificateRefs or WellKnownCACertificates may be specified, not both.
WellKnownCACertificates specifies whether system CA certificates may be used in the TLS handshake between the gateway and backend pod. If WellKnownCACertificates is unspecified or empty (""), then CACertificateRefs must be specified with at least one entry for a valid configuration. Only one of CACertificateRefs or WellKnownCACertificates may be specified, not both.
insecureSkipVerify
boolean
false
false
InsecureSkipVerify indicates whether the upstream’s certificate verification should be skipped. Defaults to “false”.
SNI specifies the fixed SNI value used when establishing an upstream TLS connection to the backend. Envoy Gateway will use the HTTP host header value for SNI, when all resources referenced in BackendRefs are: 1. Backend resources that do not set SNI, or 2. Service/ServiceImport resources that do not have a BackendTLSPolicy attached to them If a BackendTLSPolicy is attached to the Backend resource, the BackendTLSPolicy’s validation.hostname value takes precedence over this field. If no BackendTLSPolicy validation.hostname applies and both this field and AutoSNIFromEndpointHostname are unset, Envoy Gateway configures Envoy to set the upstream SNI from the downstream HTTP host/authority header.
autoSNIFromEndpointHostname
boolean
false
AutoSNIFromEndpointHostname indicates whether the upstream endpoint’s hostname should be used as the SNI value when establishing a TLS connection to the backend. This uses the resolved hostname of the upstream endpoint (e.g., from the Backend Endpoints list), rather than a static value. Mutually exclusive with SNI. When a BackendTLSPolicy is attached, its Hostname value takes precedence and AutoSNIFromEndpointHostname is ignored.
status defines the current status of BackendTrafficPolicy.
BackendTrafficPolicySpec
BackendTrafficPolicySpec defines the desired state of BackendTrafficPolicy.
Backend-targeted BackendTrafficPolicy (Service/ServiceImport/Backend targets) only applies to
a backend that resolves into a merged Envoy cluster (requires the MergeBackends EnvoyProxy
feature). A backend that never merges for any reason does not get the policy applied.
TargetRef is the name of the resource this policy is being attached to. This policy and the TargetRef MUST be in the same namespace for this Policy to have effect Deprecated: use targetRefs/targetSelectors instead. This field will be removed in v1.11.
targetRefs
LocalPolicyTargetReferenceWithSectionName array
true
TargetRefs are the names of the Gateway resources this policy is being attached to.
HTTP3 enables HTTP/3 for backend connections. HTTP/3 always runs over TLS, so the backend must be configured with TLS through a BackendTLSPolicy or the Backend’s spec.tls. HTTP/3 is only supported for the backends of a route, through BackendTrafficPolicy. It is rejected for the backends of other resources, such as the external services of a SecurityPolicy or EnvoyExtensionPolicy and the sinks of an EnvoyProxy.
HTTP1 provides HTTP/1 configuration for backend connections. When both this field and the deprecated HTTP1 field on ClientTrafficPolicy are set, this field takes precedence for backend (upstream) traffic. Behavior when targeting route kinds that do not use HTTP/1: - GRPCRoute, TCPRoute, TLSRoute, UDPRoute: targeting these route kinds directly adds a Warning condition on the policy; the field is ignored. - Gateway / ListenerSet / sectionName targets: this field is silently ignored for any GRPCRoute, TCPRoute, TLSRoute, or UDPRoute destinations beneath that target; no warning is emitted. - gRPC-only external services (ExtProc, gRPC ExtAuth, ALS, OpenTelemetry access log/metrics, tracing providers): rejected at admission on their own BackendSettings via separate validation rules.
Retry provides more advanced usage, allowing users to customize the number of retries, retry fallback strategy, and retry triggering conditions. If not set, retry will be disabled.
MergeType determines how this configuration is merged with existing BackendTrafficPolicy configurations targeting a parent resource. When set, this configuration will be merged into the closest parent BackendTrafficPolicy in the route’s attachment hierarchy (for example, one targeting a Gateway, Gateway listener, ListenerSet, or ListenerSet listener). This field can only be set when targeting xRoute or backend (Service/ServiceImport/Backend) resources, and is required when targeting a backend. If unset, no merging occurs, and only the most specific configuration takes effect.
FaultInjection defines the fault injection policy to be applied. This configuration can be used to inject delays and abort requests to mimic failure scenarios such as service failures and overloads
AdmissionControl defines the admission control policy to be applied. This configuration probabilistically rejects requests based on the success rate of previous requests in a configurable sliding time window.
useClientProtocol
boolean
false
UseClientProtocol configures Envoy to prefer sending requests to backends using the same HTTP protocol that the incoming request used. Defaults to false, which means that Envoy will use the protocol indicated by the attached BackendRef.
The compressor config for the http streams. This provides more granular control over compression configuration. Order matters: The first compressor in the list is preferred when q-values in Accept-Encoding are equal.
ResponseOverride defines the configuration to override specific responses with a custom one. If multiple configurations are specified, the first one to match wins.
HTTPUpgrade defines the configuration for HTTP protocol upgrades. If not specified, the default upgrade configuration (websocket) will be used. However, if requestBuffer is configured with mode BufferAndLimit, the default upgrade configuration will be ignored.
RequestBuffer configures how much of a request body Envoy is allowed to buffer for a route, and whether the gateway fully buffers each request before forwarding it upstream. A request whose buffered body exceeds the configured limit is rejected with HTTP 413 Content Too Large. How much of a request is buffered, and therefore whether the limit acts as a maximum request body size, depends on the mode: see the mode field. Buffering increases memory usage for Envoy that should be accounted for in your deployment settings.
Telemetry configures the telemetry settings for the policy target (Gateway or xRoute). This will override the telemetry settings in the EnvoyProxy resource.
RoutingType can be set to “Service” to use the Service Cluster IP for routing to the backend, or it can be set to “Endpoint” to use Endpoint routing. When specified, this overrides the EnvoyProxy-level setting for the relevant targetRefs. If not specified, the EnvoyProxy-level setting is used.
BackendTypeEndpoints defines the type of the backend as Endpoints.
DynamicResolver
BackendTypeDynamicResolver defines the type of the backend as DynamicResolver. When a backend is of type DynamicResolver, the Envoy will resolve the upstream ip address and port from the host header of the incoming request. If the ip address is directly set in the host header, the Envoy will use the ip address and port as the upstream address. If the hostname is set in the host header, the Envoy will resolve the ip address and port from the hostname using the DNS resolver.
KubernetesService
BackendTypeKubernetesService defines the type of the backend as a Kubernetes Service. When a backend is of type KubernetesService, Envoy Gateway watches the EndpointSlices of the referenced Service and programs them as EDS endpoints, the same as it does for a Service backendRef. This lets the Backend-only settings, such as TLS and appProtocols, be layered on top of Service endpoint semantics instead of a DNS cluster.
BackendUtilization
BackendUtilization defines configuration for Envoy’s Backend Utilization policy.
It uses Open Resource Cost Application (ORCA) load metrics reported by endpoints to make load balancing decisions.
These metrics are typically sent by the backend service in response headers or trailers.
The backend should report these metrics in header/trailer as one of the following formats:
Binary: endpoint-load-metrics-bin with base64-encoded serialized OrcaLoadReport proto.
JSON: endpoint-load-metrics with JSON-encoded OrcaLoadReport proto, e.g., JSON {"cpu_utilization": 0.3}.
TEXT: endpoint-load-metrics with comma-separated key-value pairs, e.g., TEXT cpu=0.3,mem=0.8.
By default, Envoy Gateway removes these ORCA response headers/trailers before sending the response to the client
(see KeepResponseHeaders). If you need the downstream client to see them, set KeepResponseHeaders to true.
See Envoy proto: envoy.extensions.load_balancing_policies.client_side_weighted_round_robin.v3.ClientSideWeightedRoundRobin
See ORCA Load Report proto: xds.data.orca.v3.orca_load_report.proto
How often endpoint weights are recalculated. Values less than 100ms are capped at 100ms. Default 1s.
errorUtilizationPenaltyPercent
integer
false
ErrorUtilizationPenaltyPercent adjusts endpoint weights based on the error rate (eps/qps). This is expressed as a percentage-based integer where 100 represents 1.0, 150 represents 1.5, etc. For example: - 100 => 1.0x - 120 => 1.2x - 200 => 2.0x Must be non-negative.
metricNamesForComputingUtilization
string array
false
Metric names used to compute utilization if application_utilization is not set. For map fields in ORCA proto, use the form “<map_field>.”, e.g., “named_metrics.foo”.
keepResponseHeaders
boolean
false
false
KeepResponseHeaders keeps the ORCA load report headers/trailers before sending the response to the client. Defaults to false.
OutOfBand enables out-of-band ORCA load reporting. When set, Envoy opens a server-streaming gRPC connection to each endpoint’s xds.service.orca.v3.OpenRcaService/StreamCoreMetrics and pulls load reports periodically, instead of relying on in-band ORCA metrics carried in response headers/trailers. The backend must implement OpenRcaService for this to take effect.
BandwidthLimitRequestConfig
BandwidthLimitRequestConfig defines the bandwidth limit configuration for the request direction.
Prefix is prepended to each trailer header name. If not set, no prefix is added and the trailers are named as-is. For example, setting “x-eg” produces trailers such as “x-eg-bandwidth-request-delay-ms”, while leaving it unset produces “bandwidth-request-delay-ms”. The following four trailers can be added: “bandwidth-request-delay-ms” is delay time in milliseconds it took for the request stream transfer including request body transfer time and the time added by the filter. “bandwidth-response-delay-ms” is delay time in milliseconds it took for the response stream transfer including response body transfer time and the time added by the filter. “bandwidth-request-filter-delay-ms” is delay time in milliseconds in request stream transfer added by the filter. “bandwidth-response-filter-delay-ms” is delay time in milliseconds that added by the filter.
BandwidthLimitSpec
BandwidthLimitSpec defines the desired state of BandwidthLimit.
The Kubernetes secret which contains the username-password pairs in htpasswd format, used to verify user credentials in the “Authorization” header. This is an Opaque secret. The username-password pairs should be stored in the key “.htpasswd”. As the key name indicates, the value needs to be the htpasswd format, for example: “user1:{SHA}hashed_user1_password”. Right now, only SHA hash algorithm is supported. Reference to https://httpd.apache.org/docs/2.4/programs/htpasswd.html for more details.
forwardUsernameHeader
string
false
This field specifies the header name to forward a successfully authenticated user to the backend. The header will be added to the request with the username as the value. If it is not specified, the username will not be forwarded.
BodyToExtAuth
BodyToExtAuth defines the Body to Ext Auth configuration
MaxRequestBytes is the maximum size of a message body that the filter will hold in memory. Envoy will return HTTP 413 and will not initiate the authorization process when buffer reaches the number set in this field. Note that this setting will have precedence over failOpen mode. Defaults to 32768 bytes (32KiB), which matches the default per-connection buffer limit.
packAsBytes
boolean
false
PackAsBytes, when true, sends the request body to the external authorization service as raw bytes, populating the raw_body field of the HTTP request attribute context. Otherwise, the body is sent as a UTF-8 string in the body field. This field is only supported for gRPC external authorization services. Defaults to false.
BootstrapType
Underlying type:string
BootstrapType defines the types of bootstrap supported by Envoy Gateway.
Merge merges the provided bootstrap with the default one. The provided bootstrap can add or override a value within a map, or add a new value to a list. Please note that the provided bootstrap can’t override a value within a list.
Replace
Replace replaces the default bootstrap with the provided one.
JSONPatch
JSONPatch applies the provided JSONPatches to the default bootstrap.
Quality controls the main compression speed-density lever, from 0 to 11. The higher the quality, the slower the compression. If not set, defaults to 3.
EncoderMode tunes the encoder for a specific input. If not set, defaults to Default.
windowBits
integer
false
WindowBits represents the base two logarithm of the compressor’s window size, from 10 to 24. Larger window results in better compression at the expense of memory usage. If not set, defaults to 18.
inputBlockBits
integer
false
InputBlockBits represents the base two logarithm of the compressor’s input block size, from 16 to 24. Larger input block results in better compression at the expense of memory usage. If not set, defaults to 24.
chunkSize
integer
false
ChunkSize is the size in bytes of the compressor’s next output buffer, from 4096 to 65536. If not set, defaults to 4096.
disableLiteralContextModeling
boolean
false
DisableLiteralContextModeling disables the “literal context modeling” format feature. This flag is a “decoding-speed vs compression ratio” trade-off. If not set, defaults to false.
BrotliEncoderMode
Underlying type:string
BrotliEncoderMode defines the modes to tune the Brotli encoder for a specific input.
CIDR defines a CIDR Address range.
A CIDR can be an IPv4 address range such as “192.168.1.0/24” or an IPv6 address range such as “2001:0db8:11a3:09d7::/64”.
AllowOrigins defines the origins that are allowed to make requests. It specifies the allowed origins in the Access-Control-Allow-Origin CORS response header. The value “*” allows any origin to make requests.
AllowOriginRegexes defines regular expressions that are matched against the Origin header. It specifies additional allowed origins in the Access-Control-Allow-Origin CORS response header. An origin is allowed when it matches any entry in AllowOrigins or AllowOriginRegexes.
allowMethods
string array
false
AllowMethods defines the methods that are allowed to make requests. It specifies the allowed methods in the Access-Control-Allow-Methods CORS response header.. The value “*” allows any method to be used.
allowHeaders
string array
false
AllowHeaders defines the headers that are allowed to be sent with requests. It specifies the allowed headers in the Access-Control-Allow-Headers CORS response header.. The value “*” allows any header to be sent.
exposeHeaders
string array
false
ExposeHeaders defines which response headers should be made accessible to scripts running in the browser. It specifies the headers in the Access-Control-Expose-Headers CORS response header.. The value “*” allows any header to be exposed.
MaxAge defines how long the results of a preflight request can be cached. It specifies the value in the Access-Control-Max-Age CORS response header..
allowCredentials
boolean
false
AllowCredentials indicates whether a request can include user credentials like cookies, authentication headers, or TLS client certificates. It specifies the value in the Access-Control-Allow-Credentials CORS response header.
CORSOriginRegex
Underlying type:string
CORSOriginRegex is a regular expression that is matched against the full Origin header value,
including the scheme and the port if present.
The regex string must adhere to the syntax documented in
https://github.com/google/re2/wiki/Syntax, except for the \C escape sequence,
which is not supported.
A regular expression that matches the literal string “” is rejected.
The value “” in AllowOrigins allows any origin.
CSRF defines the configuration for the Cross-Site Request Forgery (CSRF) filter.
The CSRF filter checks that the Origin header in HTTP requests matches the destination,
preventing cross-origin mutating requests (POST, PUT, DELETE, PATCH) from being processed.
GET and HEAD requests are always allowed.
ShadowFraction represents the fraction of requests for which the CSRF policy is evaluated in shadow (dry-run) mode. For these requests, the filter records whether the request would have been allowed or rejected in the csrf.request_valid and csrf.request_invalid stats, but always lets the request through. The remaining requests are enforced, i.e. a mutating request with a missing or non-matching Origin header is rejected with a 403. Defaults to 0% (all requests are enforced) if not specified. Set it to 100% to dry run the filter, watch the stats to find origins that would be rejected, then lower it to roll enforcement out gradually.
AdditionalOrigins specifies additional origins that are allowed to make mutating requests, beyond the destination origin. A request whose Origin header matches one of them is allowed. The value “*” allows any origin, which effectively disables origin validation. Note: Envoy’s CSRF filter compares the host and port of the origin only, so the scheme is ignored: “https://www.example.com” and “http://www.example.com” are equivalent here, and both allow the request regardless of the scheme the client used.
CircuitBreaker
CircuitBreaker defines the Circuit Breaker configuration.
The maximum number of connections that Envoy will establish to the referenced backend defined within a xRoute rule.
maxPendingRequests
integer
false
1024
The maximum number of pending requests that Envoy will queue to the referenced backend defined within a xRoute rule.
maxParallelRequests
integer
false
1024
The maximum number of parallel requests that Envoy will make to the referenced backend defined within a xRoute rule.
maxParallelRetries
integer
false
1024
The maximum number of parallel retries that Envoy will make to the referenced backend defined within a xRoute rule.
maxRequestsPerConnection
integer
false
The maximum number of requests that Envoy will make over a single connection to the referenced backend defined within a xRoute rule. Default: unlimited.
RetryBudget provides settings for retry budget, which limits the number of retries in a given percentage. RetryBudget take precedence over maxParallelRetries.
ClaimToHeader
ClaimToHeader defines a configuration to convert JWT claims into HTTP headers
Header defines the name of the HTTP request header that the JWT Claim will be saved into.
claim
string
false
Claim is the JWT Claim that should be saved into the header : it can be a nested claim of type (eg. “claim.nested.key”, “sub”). The nested claim name must use dot “." to separate the JSON name path. Because the name is always split on “.”, a claim whose own name contains a dot – a URI-namespaced claim such as “https://example.com/claims/tenant_name" commonly emitted by OIDC providers – cannot be addressed this way. Use ClaimPath for those claims instead. Exactly one of Claim or ClaimPath must be specified.
claimPath
string array
false
ClaimPath is the path to the claim to copy, given as an explicit list of segments. Each segment is matched in full against a key of the enclosing JSON object, so claim names containing dots are addressable. For example, a top-level claim named “https://example.com/claims/tenant_name" is selected with: claimPath: - “https://example.com/claims/tenant_name" and a nested claim \{"nested": \{"claim": \{"key": "value"\}\}\} is selected with: claimPath: - nested - claim - key Exactly one of Claim or ClaimPath must be specified.
ClientConnection
ClientConnection allows users to configure connection-level settings of client
BufferLimit provides configuration for the maximum buffer size in bytes for each incoming connection. BufferLimit applies to connection streaming (maybe non-streaming) channel between processes, it’s in user space. For example, 20Mi, 1Gi, 256Ki etc. Note that when the suffix is not provided, the value is interpreted as bytes. Default: 32768 bytes.
maxAcceptPerSocketEvent
integer
false
1
MaxAcceptPerSocketEvent provides configuration for the maximum number of connections to accept from the kernel per socket event. If there are more than MaxAcceptPerSocketEvent connections pending accept, connections over this threshold will be accepted in later event loop iterations. Defaults to 1 and can be disabled by setting to 0 for allowing unlimited accepted connections.
ClientIPDetectionSettings
ClientIPDetectionSettings provides configuration for determining the original client IP address for requests.
Exactly one of XForwardedFor, CustomHeader, or DirectSourceIP must be set.
DirectSourceIP configures the geoip filter to use the downstream connection source address (the TCP peer of the connection terminated by Envoy) as the client IP. Use this in L4-transparent topologies where a load balancer preserves the original client source IP at TCP level and does not populate XFF or a custom header — for example, AWS NLB with target-type=instance + externalTrafficPolicy=Local, or Azure Standard Load Balancer. Mutually exclusive with XForwardedFor and CustomHeader.
ClientIPGeoLocation
ClientIPGeoLocation specifies geolocation-based match criteria for authorization.
Max specifies the maximal TLS protocol version to allow The default is TLS 1.3 if this is not specified.
ciphers
string array
false
Ciphers specifies the set of cipher suites supported when negotiating TLS 1.0 - 1.2. This setting has no effect for TLS 1.3. For Envoy TLS cipher suite configuration semantics and default cipher lists, see the Envoy documentation: https://www.envoyproxy.io/docs/envoy/latest/api-v3/extensions/transport_sockets/tls/v3/common.proto#extensions-transport-sockets-tls-v3-tlsparameters Supported cipher suite names: - ECDHE-ECDSA-AES128-GCM-SHA256 - ECDHE-RSA-AES128-GCM-SHA256 - ECDHE-ECDSA-AES256-GCM-SHA384 - ECDHE-RSA-AES256-GCM-SHA384 - ECDHE-ECDSA-CHACHA20-POLY1305 - ECDHE-RSA-CHACHA20-POLY1305 - ECDHE-ECDSA-AES128-SHA - ECDHE-RSA-AES128-SHA - AES128-GCM-SHA256 - AES128-SHA - ECDHE-ECDSA-AES256-SHA - ECDHE-RSA-AES256-SHA - AES256-GCM-SHA384 - AES256-SHA Supported IANA/RFC aliases: - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 - TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 - TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 - TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA - TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA - TLS_RSA_WITH_AES_128_GCM_SHA256 - TLS_RSA_WITH_AES_128_CBC_SHA - TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA - TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA - TLS_RSA_WITH_AES_256_GCM_SHA384 - TLS_RSA_WITH_AES_256_CBC_SHA In non-FIPS Envoy Proxy builds the default cipher list is: - [ECDHE-ECDSA-AES128-GCM-SHA256|ECDHE-ECDSA-CHACHA20-POLY1305] - [ECDHE-RSA-AES128-GCM-SHA256|ECDHE-RSA-CHACHA20-POLY1305] - ECDHE-ECDSA-AES256-GCM-SHA384 - ECDHE-RSA-AES256-GCM-SHA384 In builds using BoringSSL FIPS the default cipher list is: - ECDHE-ECDSA-AES128-GCM-SHA256 - ECDHE-RSA-AES128-GCM-SHA256 - ECDHE-ECDSA-AES256-GCM-SHA384 - ECDHE-RSA-AES256-GCM-SHA384
ecdhCurves
string array
false
ECDHCurves specifies the set of supported ECDH curves. In non-FIPS Envoy Proxy builds the default curves are: - X25519 - P-256 In builds using BoringSSL FIPS the default curve is: - P-256
signatureAlgorithms
string array
false
SignatureAlgorithms specifies which signature algorithms the listener should support.
ALPNProtocols supplies the list of ALPN protocols that should be exposed by the listener or used by the proxy to connect to the backend. Defaults: 1. HTTPS Routes: h2 and http/1.1 are enabled in listener context. 2. Other Routes: ALPN is disabled. 3. Backends: proxy uses the appropriate ALPN options for the backend protocol. When an empty list is provided, the ALPN TLS extension is disabled. Defaults to [h2, http/1.1] if not specified. Typical Supported values are: - http/1.0 - http/1.1 - h2
Fingerprints specifies TLS client fingerprinting. When specified, a JAX fingerprint derived from the client’s TLS handshake is generated. The fingerprint can be logged in access logs or forwarded to upstream services using request headers. Fingerprinting is disabled if not specified. Supported values are: - JA3 - JA4
TargetRef is the name of the resource this policy is being attached to. This policy and the TargetRef MUST be in the same namespace for this Policy to have effect Deprecated: use targetRefs/targetSelectors instead. This field will be removed in v1.11.
targetRefs
LocalPolicyTargetReferenceWithSectionName array
true
TargetRefs are the names of the Gateway resources this policy is being attached to.
TcpKeepalive settings associated with the downstream client connection. If defined, sets SO_KEEPALIVE on the listener socket to enable TCP Keepalives. Disabled by default.
enableProxyProtocol
boolean
false
EnableProxyProtocol interprets the ProxyProtocol header and adds the Client Address into the X-Forwarded-For header. Note Proxy Protocol must be present when this field is set, else the connection is closed. Deprecated: Use ProxyProtocol instead. This field will be removed in v1.11.
ProxyProtocol configures the Proxy Protocol settings. When configured, the Proxy Protocol header will be interpreted and the Client Address will be added into the X-Forwarded-For header. If both EnableProxyProtocol and ProxyProtocol are set, ProxyProtocol takes precedence.
Scheme configures how the :scheme pseudo-header is set for requests forwarded to backends. - Preserve (default): Preserves the :scheme from the original client request. Use this when backends need to know the original client scheme for URL generation or redirects. - MatchBackend: Sets the :scheme to match the backend transport protocol. If the backend uses TLS, the scheme is “https”, otherwise “http”. Use this when backends require the scheme to match the actual transport protocol, such as strictly HTTPS services that validate the :scheme header.
ClientValidationContext
ClientValidationContext holds configuration that can be used to validate the client initiating the TLS connection
to the Gateway.
By default, no client specific configuration is validated.
Optional set to true accepts connections even when a client doesn’t present a certificate. Defaults to false, which rejects connections without a valid client certificate. Deprecated: Use Mode instead.
CACertificateRefs contains one or more references to Kubernetes objects that contain TLS certificates of the Certificate Authorities that can be used as a trust anchor to validate the certificates presented by the client. A single reference to a Kubernetes ConfigMap or a Kubernetes Secret, with the CA certificate in a key named ca.crt is currently supported. References to a resource in different namespace are invalid UNLESS there is a ReferenceGrant in the target namespace that allows the certificate to be attached.
spkiHashes
string array
false
An optional list of base64-encoded SHA-256 hashes. If specified, Envoy will verify that the SHA-256 of the DER-encoded Subject Public Key Information (SPKI) of the presented certificate matches one of the specified values. Setting this requires a client certificate, so it cannot be combined with mode VerifyIfGiven or the deprecated optional: true.
certificateHashes
string array
false
An optional list of hex-encoded SHA-256 hashes. If specified, Envoy will verify that the SHA-256 of the DER-encoded presented certificate matches one of the specified values. Setting this requires a client certificate, so it cannot be combined with mode VerifyIfGiven or the deprecated optional: true.
An optional list of Subject Alternative name matchers. If specified, Envoy will verify that the Subject Alternative Name of the presented certificate matches one of the specified matchers. Setting this requires a client certificate, so it cannot be combined with mode VerifyIfGiven or the deprecated optional: true.
Crl specifies the crl configuration that can be used to validate the client initiating the TLS connection
allowExpiredCertificate
boolean
false
AllowExpiredCertificate permits client certificates that have expired but are otherwise valid (CA chain, signature). When true, Envoy skips the NotAfter check during client certificate validation. Defaults to false.
ClientValidationModeType
Underlying type:string
ClientValidationModeType defines how a Gateway or Listener validates client certificates.
Request indicates that a client certificate is requested during the TLS handshake but does not require one.
RequireAny
RequireAny indicates that a client certificate is required during the handshake, but the connection is permitted even when the client certificate verification fails.
VerifyIfGiven
VerifyIfGiven indicates that a client certificate is requested but not required. If presented, the certificate must be valid. SubjectAltNames, CertificateHashes and SPKIHashes cannot be used with this mode: Envoy requires a client certificate whenever they are set.
RequireAndVerify
RequireAndVerify indicates that a valid client certificate must be presented during the handshake and validated using CA certificates defined in CACertificateRefs.
ClusterSettings
ClusterSettings contains CDS-only fields that configure the upstream Envoy Cluster.
HTTP3 enables HTTP/3 for backend connections. HTTP/3 always runs over TLS, so the backend must be configured with TLS through a BackendTLSPolicy or the Backend’s spec.tls. HTTP/3 is only supported for the backends of a route, through BackendTrafficPolicy. It is rejected for the backends of other resources, such as the external services of a SecurityPolicy or EnvoyExtensionPolicy and the sinks of an EnvoyProxy.
HTTP1 provides HTTP/1 configuration for backend connections. When both this field and the deprecated HTTP1 field on ClientTrafficPolicy are set, this field takes precedence for backend (upstream) traffic. Behavior when targeting route kinds that do not use HTTP/1: - GRPCRoute, TCPRoute, TLSRoute, UDPRoute: targeting these route kinds directly adds a Warning condition on the policy; the field is ignored. - Gateway / ListenerSet / sectionName targets: this field is silently ignored for any GRPCRoute, TCPRoute, TLSRoute, or UDPRoute destinations beneath that target; no warning is emitted. - gRPC-only external services (ExtProc, gRPC ExtAuth, ALS, OpenTelemetry access log/metrics, tracing providers): rejected at admission on their own BackendSettings via separate validation rules.
MinContentLength defines the minimum response size in bytes to apply compression. Responses smaller than this threshold will not be compressed. Must be at least 30 bytes as enforced by Envoy Proxy. Note that when the suffix is not provided, the value is interpreted as bytes. Default: 30 bytes
CompressorType
Underlying type:string
CompressorType defines the types of compressor library supported by Envoy Gateway.
MaxConnectionDuration is the maximum amount of time a connection can remain established (usually via TCP/HTTP Keepalive packets) before being drained and/or closed. If not specified, there is no limit.
maxConnectionDurationJitter
integer
false
MaxConnectionDurationJitter adds a random extra amount of time to each connection’s MaxConnectionDuration, up to this percentage of that duration. This keeps connections opened together from expiring at the same moment. Requires MaxConnectionDuration. If not specified, no jitter is added.
maxRequestsPerConnection
integer
false
MaxRequestsPerConnection defines the maximum number of requests allowed over a single connection. If not specified, there is no limit. Setting this parameter to 1 will effectively disable keep alive.
MaxStreamDuration is the maximum amount of time to keep alive an http stream. When the limit is reached the stream will be reset independent of any other timeouts. If not specified, no value is set.
ConsistentHash
ConsistentHash defines the configuration related to the consistent hash
load balancer policy.
Header configures the header hash policy when the consistent hash type is set to Header. Deprecated: use Headers instead. This field will be removed in v1.11.
SourceIPConsistentHashType hashes based on the source IP address.
Header
HeaderConsistentHashType hashes based on a request header. Deprecated: use HeadersConsistentHashType instead. This value will be removed in v1.11.
Headers
HeadersConsistentHashType hashes based on multiple request headers.
Cookie
CookieConsistentHashType hashes based on a cookie.
QueryParams
QueryParamsConsistentHashType hashes based on a multiple query parameter.
ContextExtension
ContextExtension is analogous to http_request.headers, however these
contents will not be sent to the upstream server. This provides an
extension mechanism for sending additional information to the auth server
without modifying the proto definition. It maps to the internal opaque
context in the filter chain.
Name of the cookie to hash. If this cookie does not exist in the request, Envoy will generate a cookie and set the TTL on the response back to the client based on Layer 4 attributes of the backend endpoint, to ensure that these future requests go to the same backend endpoint. Make sure to set the TTL field for this case.
CookieMatchExact matches the exact value of the cookie.
RegularExpression
CookieMatchRegularExpression matches a regular expression against the value of the cookie. The regex string must adhere to the syntax documented in https://github.com/google/re2/wiki/Syntax.
CrlContext
CrlContext holds certificate revocation list configuration that can be used to validate the client initiating the TLS connection
Refs contains one or more references to a Kubernetes ConfigMap or a Kubernetes Secret, containing the certificate revocation list in PEM format Expects the content in a key named ca.crl. References to a resource in different namespace are invalid UNLESS there is a ReferenceGrant in the target namespace that allows the crl to be attached.
onlyVerifyLeafCertificate
boolean
false
If this option is set to true, Envoy will only verify the certificate at the end of the certificate chain against the CRL. Defaults to false, which will verify the entire certificate chain against the CRL.
Name of the header containing the original downstream remote address, if present.
failClosed
boolean
false
FailClosed is a switch used to control the flow of traffic when client IP detection fails. If set to true, the listener will respond with 403 Forbidden when the client IP address cannot be determined.
CustomRedirect
CustomRedirect contains configuration for returning a custom redirect.
Hostname is the hostname to be used in the value of the Location header in the response. When empty, the hostname in the Host header of the request is used.
Path defines parameters used to modify the path of the incoming request. The modified path is then used to construct the Location header. When empty, the request path is used as-is. Only ReplaceFullPath path modifier is supported currently.
Port is the port to be used in the value of the Location header in the response. If redirect scheme is not-empty, the well-known port associated with the redirect scheme will be used. Specifically “http” to port 80 and “https” to port 443. If the redirect scheme does not have a well-known port or redirect scheme is empty, the listener port of the Gateway will be used. Port will not be added in the ‘Location’ header if scheme is HTTP and port is 80 or scheme is HTTPS and port is 443.
statusCode
integer
false
302
StatusCode is the HTTP status code to be used in response.
CustomResponse
CustomResponse defines the configuration for returning a custom response.
Header defines headers to add, set or remove from the response. This allows the response policy to append, add or override headers of the final response before it is sent to a downstream client. Note: Header removal is not supported for responseOverride.
ValueRef contains the contents of the body specified as a local object reference. Only a reference to ConfigMap is supported. The value of key response.body in the ConfigMap will be used as the response body. If the key is not found, the first value in the ConfigMap will be used.
CustomResponseMatch
CustomResponseMatch defines the configuration for matching a user response to return a custom one.
When more than one of statusCodes, requestHeaders and responseHeaders is specified, all of them must match.
Request headers to match on. The match evaluates to true if all matches are successful. Note that the request headers are not available for all Envoy-generated responses, in which case a request header match never evaluates to true.
DNSRefreshRate specifies the rate at which DNS records should be refreshed. Defaults to 30 seconds.
respectDnsTtl
boolean
false
RespectDNSTTL indicates whether the DNS Time-To-Live (TTL) should be respected. If the value is set to true, the DNS refresh rate will be set to the resource record’s TTL. Defaults to true.
LookupFamily determines how Envoy would resolve DNS for Routes where the backend is specified as a fully qualified domain name (FQDN). If set, this configuration overrides other defaults.
DNSLookupFamily
Underlying type:string
DNSLookupFamily defines the behavior of Envoy when resolving DNS for hostnames
IPv4DNSLookupFamily means the DNS resolver will first perform a lookup for addresses in the IPv4 family.
IPv6
IPv6DNSLookupFamily means the DNS resolver will first perform a lookup for addresses in the IPv6 family.
IPv4Preferred
IPv4PreferredDNSLookupFamily means the DNS resolver will first perform a lookup for addresses in the IPv4 family and fallback to a lookup for addresses in the IPv6 family.
IPv6Preferred
IPv6PreferredDNSLookupFamily means the DNS resolver will first perform a lookup for addresses in the IPv6 family and fallback to a lookup for addresses in the IPv4 family.
IPv4AndIPv6
IPv4AndIPv6DNSLookupFamily mean the DNS resolver will perform a lookup for both IPv4 and IPv6 families, and return all resolved addresses. When this is used, Happy Eyeballs will be enabled for upstream connections.
Debounce
Debounce defines how Envoy Gateway coalesces bursts of resource changes before
reconciling them into new configuration for Envoy Proxy.
Without debouncing, each resource change costs a full reconcile, so a burst of
changes rebuilds the resource tree, retranslates and pushes once per change even
though only the resulting state matters. That spends control plane CPU on work that
is immediately superseded, and makes the proxies apply configuration that will be
replaced moments later.
Debouncing merges changes that arrive close together into a single reconcile, so the
cost of a burst approaches that of a single change. The tradeoff is that propagation
of a change, and of the status derived from it, may be delayed by up to Max.
Debouncing is opt in: it is on whenever this field is set, and off when it is
left unset.
This applies to the Kubernetes provider only. It has no effect when the resource
provider is File, whose reconcile loop is driven directly by file change events.
After is the quiet period. A pending batch of changes is flushed once no new change has arrived for this duration, so isolated changes still propagate promptly. If unspecified, defaults to 100ms.
Max bounds how long a change may be held before a flush is forced. Under sustained churn the quiet period never elapses, so this caps how far behind the proxies’ configuration can fall. Must be greater than or equal to After. If unspecified, defaults to 10s.
DirectSourceIPSettings
DirectSourceIPSettings configures client IP detection from the downstream
connection source address. It currently has no fields; its presence opts the listener
into using the TCP peer address as the client IP.
DrainStrategyGradual drains HTTP connections progressively within the drain timeout.
Immediate
DrainStrategyImmediate drains all HTTP connections once the drain process starts.
DynamicModule
DynamicModule defines a dynamic module HTTP filter to be loaded by Envoy.
The module must be registered in the EnvoyProxy resource’s dynamicModules
allowlist by the infrastructure operator.
Name references a dynamic module registered in the EnvoyProxy resource’s dynamicModules list. The referenced module must exist in the registry; otherwise, the policy will be rejected.
filterName
string
false
FilterName identifies a specific filter implementation within the dynamic module. A single shared library can contain multiple filter implementations. This value is passed to the module’s HTTP filter config init function to select the appropriate implementation. If not specified, defaults to an empty string.
Config is the configuration for the dynamic module filter. This is serialized as JSON and passed to the module’s initialization function.
terminalFilter
boolean
false
false
TerminalFilter indicates that this dynamic module handles requests without requiring an upstream backend. The module is responsible for generating and sending the response to downstream directly. Defaults to false.
DynamicModuleEntry
DynamicModuleEntry defines a dynamic module that is registered and allowed
for use by EnvoyExtensionPolicy resources.
Source defines where the dynamic module code is loaded from.
doNotClose
boolean
false
false
DoNotClose prevents the module from being unloaded with dlclose when no more references exist. This is useful for modules that maintain global state that should not be destroyed on configuration updates. Defaults to false.
loadGlobally
boolean
false
false
LoadGlobally loads the dynamic module with the RTLD_GLOBAL flag. By default, modules are loaded with RTLD_LOCAL to avoid symbol conflicts. Set this to true when the module needs to share symbols with other dynamic libraries it loads. Defaults to false.
DynamicModuleLBPolicy
DynamicModuleLBPolicy configures a custom load balancing algorithm
implemented as a dynamic module (runtime-loaded shared library).
The module must be registered in the EnvoyProxy resource’s dynamicModules allowlist.
Name references a dynamic module registered in the EnvoyProxy resource’s dynamicModules list. The referenced module must exist in the registry; otherwise, the policy will be rejected.
lbPolicyName
string
true
LBPolicyName identifies a specific load balancer implementation within the dynamic module. A single shared library can contain multiple LB policy implementations. This value is passed to the module’s initialization function to select the appropriate implementation.
LocalDynamicModuleSourceType specifies a module loaded from the local filesystem.
Remote
RemoteDynamicModuleSourceType specifies a module fetched from a remote source.
EndpointOverride
EndpointOverride defines the configuration for endpoint override.
This allows endpoint picking to be implemented based on request headers or metadata.
It extracts selected override endpoints from the specified sources (request headers, metadata, etc.).
If no valid endpoint in the override list, then the configured load balancing policy is used as fallback.
Header defines the header to get the override endpoint addresses. The header value must specify at least one endpoint in IP:Port format or multiple endpoints in IP:Port,IP:Port,... format. For example 10.0.0.5:8080 or [2600:4040:5204::1574:24ae]:80. The IPv6 address is enclosed in square brackets.
EnvironmentCustomTag
EnvironmentCustomTag adds value from environment variable to each span.
TargetRef is the name of the resource this policy is being attached to. This policy and the TargetRef MUST be in the same namespace for this Policy to have effect Deprecated: use targetRefs/targetSelectors instead. This field will be removed in v1.11.
targetRefs
LocalPolicyTargetReferenceWithSectionName array
true
TargetRefs are the names of the Gateway resources this policy is being attached to.
MergeType determines how this configuration is merged with existing EnvoyExtensionPolicy configurations targeting a parent resource. When set, this configuration will be merged into the closest parent EnvoyExtensionPolicy in the route’s attachment hierarchy (for example, one targeting a Gateway, Gateway listener, ListenerSet, or ListenerSet listener). Currently, this field can only be set when targeting xRoute resources. If unset, no merging occurs, and only the most specific configuration takes effect.
Backends declares HTTP callout dependencies for Lua, Wasm and dynamic modules. Requires extensionApis.enableExtensionBackends to be set to true in the EnvoyGateway configuration. Each name is an alias in this policy. Extensions read the generated cluster name from route metadata during a request. Initialization and independent background callbacks have no request route. Asynchronous callbacks can use bindings resolved for their request. When merging policies, a nonempty list replaces the parent’s list. Inherited references keep the namespace of the policy that declared them.
Wasm is a list of Wasm extensions to be loaded by the Gateway. Order matters, as the extensions will be loaded in the order they are defined in this list.
DynamicModule is an ordered list of dynamic module HTTP filters that should be added to the envoy filter chain. Each module must be registered in the EnvoyProxy resource’s dynamicModules allowlist. Order matters, as the filters will be loaded in the order they are defined in this list.
EnvoyFilter
Underlying type:string
EnvoyFilter defines the type of Envoy HTTP filter.
Provider defines the desired provider and provider-specific configuration. If unspecified, the Kubernetes provider is used with default configuration parameters.
Debounce defines how Envoy Gateway coalesces bursts of resource changes before reconciling them into new configuration for Envoy Proxy. If unspecified, debouncing is disabled and every change is reconciled on its own. Applies to the Kubernetes provider only.
RateLimit defines the configuration associated with the Rate Limit service deployed by Envoy Gateway required to implement the Global Rate limiting functionality. The specific rate limit service used here is the reference implementation in Envoy. For more details visit https://github.com/envoyproxy/ratelimit. This configuration is unneeded for “Local” rate limiting.
ExtensionManager defines an extension manager to register for the Envoy Gateway Control Plane. Warning: Enabling an Extension Server may lead to complete security compromise of your system. Users that control the Extension Server can inject arbitrary configuration to proxies, leading to high Confidentiality, Integrity and Availability risks.
ExtensionManagers defines multiple extension managers to register for the Envoy Gateway Control Plane. Each extension’s output becomes the next extension’s input, enabling sequential chaining. Each entry must have a unique Name field for identification. This field is mutually exclusive with ExtensionManager. Warning: Enabling Extension Servers may lead to complete security compromise of your system. Users that control Extension Servers can inject arbitrary configuration to proxies, leading to high Confidentiality, Integrity and Availability risks.
RuntimeFlags defines the runtime flags for Envoy Gateway. Unlike ExtensionAPIs, these flags are temporary and will be removed in future releases once the related features are stable.
EnvoyProxy defines the default EnvoyProxy configuration that applies to all managed Envoy Proxy fleet. This is an optional field and when provided, the settings from this EnvoyProxySpec serve as the base defaults for all Envoy Proxy instances. The hierarchy for EnvoyProxy configuration is (highest to lowest priority): 1. Gateway-level EnvoyProxy (referenced via Gateway.spec.infrastructure.parametersRef) 2. GatewayClass-level EnvoyProxy (referenced via GatewayClass.spec.parametersRef) 3. This EnvoyProxy default spec The merge strategy for a more specific EnvoyProxy is controlled by its spec.mergeType field. If mergeType is unset, the more specific EnvoyProxy completely replaces less specific settings. Note: mergeType has no effect in this default EnvoyProxySpec.
EnvoyGatewayAdmin
EnvoyGatewayAdmin defines the Envoy Gateway Admin configuration.
Resource defines the desired resource provider. This provider is used to specify the provider to be used to retrieve the resource configurations such as Gateway API resources
Infrastructure defines the desired infrastructure provider. This provider is used to specify the provider to be used to provide an environment to deploy the out resources like the Envoy Proxy data plane. Infrastructure is optional, if provider is not specified, No infrastructure provider is available.
EnvoyGatewayFileResourceProvider
EnvoyGatewayFileResourceProvider defines configuration for the File Resource provider.
LeaderElection specifies the configuration for leader election. If it’s not set up, leader election will be active by default, using Kubernetes’ standard settings.
CacheSyncPeriod determines the minimum frequency at which watched resources are synced. Note that a sync in the provider layer will not lead to a full reconciliation (including translation), unless there are actual changes in the provider resources. This option can be used to protect against missed events or issues in Envoy Gateway where resources are not requeued when they should be, at the cost of increased resource consumption. Learn more about the implications of this option: https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/cache#Options Default: 10 hours
EnvoyGatewayKubernetesCustomProvider
EnvoyGatewayKubernetesCustomProvider defines configuration for the Kubernetes provider when using a Custom provider.
LeaderElection specifies the configuration for leader election. If it’s not set up, leader election will be active by default, using Kubernetes’ standard settings.
CacheSyncPeriod determines the minimum frequency at which watched resources are synced. Note that a sync in the provider layer will not lead to a full reconciliation (including translation), unless there are actual changes in the provider resources. This option can be used to protect against missed events or issues in Envoy Gateway where resources are not requeued when they should be, at the cost of increased resource consumption. Learn more about the implications of this option: https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/cache#Options Default: 10 hours
EnvoyGatewayKubernetesInfrastructureConfiguration
EnvoyGatewayKubernetesInfrastructureConfiguration defines configuration for the Kubernetes infrastructure provider.
RateLimitDeployment defines the desired state of the Envoy ratelimit deployment resource. If unspecified, default settings for the managed Envoy ratelimit deployment resource are applied.
RateLimitHpa defines the Horizontal Pod Autoscaler settings for Envoy ratelimit Deployment. If the HPA is set, Replicas field from RateLimitDeployment will be ignored.
RateLimitDeployment defines the desired state of the Envoy ratelimit deployment resource. If unspecified, default settings for the managed Envoy ratelimit deployment resource are applied.
RateLimitHpa defines the Horizontal Pod Autoscaler settings for Envoy ratelimit Deployment. If the HPA is set, Replicas field from RateLimitDeployment will be ignored.
LeaderElection specifies the configuration for leader election. If it’s not set up, leader election will be active by default, using Kubernetes’ standard settings.
CacheSyncPeriod determines the minimum frequency at which watched resources are synced. Note that a sync in the provider layer will not lead to a full reconciliation (including translation), unless there are actual changes in the provider resources. This option can be used to protect against missed events or issues in Envoy Gateway where resources are not requeued when they should be, at the cost of increased resource consumption. Learn more about the implications of this option: https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/cache#Options Default: 10 hours
EnvoyGatewayLogComponent
Underlying type:string
EnvoyGatewayLogComponent defines a component that supports a configured logging level.
Level is the logging level. If unspecified, defaults to “info”. EnvoyGatewayLogComponent options: default/provider/gateway-api/xds-translator/xds-server/infrastructure/global-ratelimit. LogLevel options: debug/info/error/warn.
ExportInterval configures the intervening time between exports for a Sink. This option overrides any value set for the OTEL_METRIC_EXPORT_INTERVAL environment variable. If ExportInterval is less than or equal to zero, 60 seconds is used as the default.
ExportTimeout configures the time a Sink waits for an export to complete before canceling it. This option overrides any value set for the OTEL_METRIC_EXPORT_TIMEOUT environment variable. If ExportTimeout is less than or equal to zero, 30 seconds is used as the default.
EnvoyGatewayPrometheusProvider
EnvoyGatewayPrometheusProvider will expose prometheus endpoint in pull mode.
Custom defines the configuration for the Custom provider. This provider allows you to define a specific resource provider and an infrastructure provider.
EnvoyGatewayRemoteInfrastructureProvider
EnvoyGatewayRemoteInfrastructureProvider defines configuration for the Remote Infrastructure provider.
Service defines the configuration of the remote infrastructure service that the Envoy Gateway Control Plane will call through the infrastructure manager.
EnvoyGatewayResourceProvider
EnvoyGatewayResourceProvider defines configuration for the Custom Resource provider.
Provider defines the desired provider and provider-specific configuration. If unspecified, the Kubernetes provider is used with default configuration parameters.
Debounce defines how Envoy Gateway coalesces bursts of resource changes before reconciling them into new configuration for Envoy Proxy. If unspecified, debouncing is disabled and every change is reconciled on its own. Applies to the Kubernetes provider only.
RateLimit defines the configuration associated with the Rate Limit service deployed by Envoy Gateway required to implement the Global Rate limiting functionality. The specific rate limit service used here is the reference implementation in Envoy. For more details visit https://github.com/envoyproxy/ratelimit. This configuration is unneeded for “Local” rate limiting.
ExtensionManager defines an extension manager to register for the Envoy Gateway Control Plane. Warning: Enabling an Extension Server may lead to complete security compromise of your system. Users that control the Extension Server can inject arbitrary configuration to proxies, leading to high Confidentiality, Integrity and Availability risks.
ExtensionManagers defines multiple extension managers to register for the Envoy Gateway Control Plane. Each extension’s output becomes the next extension’s input, enabling sequential chaining. Each entry must have a unique Name field for identification. This field is mutually exclusive with ExtensionManager. Warning: Enabling Extension Servers may lead to complete security compromise of your system. Users that control Extension Servers can inject arbitrary configuration to proxies, leading to high Confidentiality, Integrity and Availability risks.
RuntimeFlags defines the runtime flags for Envoy Gateway. Unlike ExtensionAPIs, these flags are temporary and will be removed in future releases once the related features are stable.
EnvoyProxy defines the default EnvoyProxy configuration that applies to all managed Envoy Proxy fleet. This is an optional field and when provided, the settings from this EnvoyProxySpec serve as the base defaults for all Envoy Proxy instances. The hierarchy for EnvoyProxy configuration is (highest to lowest priority): 1. Gateway-level EnvoyProxy (referenced via Gateway.spec.infrastructure.parametersRef) 2. GatewayClass-level EnvoyProxy (referenced via GatewayClass.spec.parametersRef) 3. This EnvoyProxy default spec The merge strategy for a more specific EnvoyProxy is controlled by its spec.mergeType field. If mergeType is unset, the more specific EnvoyProxy completely replaces less specific settings. Note: mergeType has no effect in this default EnvoyProxySpec.
EnvoyGatewayTelemetry
EnvoyGatewayTelemetry defines telemetry configurations for envoy gateway control plane.
Control plane will focus on metrics observability telemetry and tracing telemetry later.
SamplingRate controls the fraction of traces that are sampled. The value is expressed as a Gateway API Fraction (numerator/denominator). If denominator is omitted, it defaults to 100.
EnvoyJSONPatchConfig
EnvoyJSONPatchConfig defines the configuration for patching a Envoy xDS Resource
using JSONPatch semantic
TargetRef is the name of the Gateway API resource this policy is being attached to. By default, attaching to Gateway is supported and when mergeGateways is enabled it should attach to GatewayClass. This Policy and the TargetRef MUST be in the same namespace for this Policy to have effect and be applied to the Gateway TargetRef
priority
integer
true
Priority of the EnvoyPatchPolicy. If multiple EnvoyPatchPolicies are applied to the same TargetRef, they will be applied in the ascending order of the priority i.e. int32.min has the highest priority and int32.max has the lowest priority. Defaults to 0.
EnvoyPatchType
Underlying type:string
EnvoyPatchType specifies the types of Envoy patching mechanisms.
JSONPatchEnvoyPatchType allows the user to patch the generated xDS resources using JSONPatch semantics. For more details on the semantics, please refer to https://datatracker.ietf.org/doc/html/rfc6902
EnvoyProxy
EnvoyProxy is the schema for the envoyproxies API.
EnvoyDeployment defines the desired state of the Envoy deployment resource. If unspecified, default settings for the managed Envoy deployment resource are applied.
EnvoyDaemonSet defines the desired state of the Envoy daemonset resource. Disabled by default, a deployment resource is used instead to provision the Envoy Proxy fleet
EnvoyService defines the desired state of the Envoy service resource. If unspecified, default settings for the managed Envoy service resource are applied.
EnvoyHpa defines the Horizontal Pod Autoscaler settings for Envoy Proxy Deployment. If the HPA is set, the Replicas field from EnvoyDeployment will be ignored, and the number of replicas is solely managed by the HPA. Use MinReplicas to control the lower bound of the replica count instead.
useListenerPortAsContainerPort
boolean
false
UseListenerPortAsContainerPort disables the port shifting feature in the Envoy Proxy. When set to false (default value), if the service port is a privileged port (1-1023), add a constant to the value converting it into an ephemeral port. This allows the container to bind to the port without needing a CAP_NET_BIND_SERVICE capability.
Type is the type of resource provider to use. A resource provider provides infrastructure resources for running the data plane, e.g. Envoy proxy, and optional auxiliary control planes. Supported types are “Kubernetes” and “Host”.
Kubernetes defines the desired state of the Kubernetes resource provider. Kubernetes provides infrastructure resources for running the data plane, e.g. Envoy proxy. If unspecified and type is “Kubernetes”, default settings for managed Kubernetes resources are applied.
Host provides runtime deployment of the data plane as a child process on the host environment. If unspecified and type is “Host”, default settings for the custom provider are applied.
EnvoyProxyProviderType
Underlying type:string
EnvoyProxyProviderType defines the types of providers supported by Envoy Proxy.
Provider defines the desired resource provider and provider-specific configuration. If unspecified, the “Kubernetes” resource provider is used with default configuration parameters.
Bootstrap defines the Envoy Bootstrap as a YAML string. Visit https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/bootstrap/v3/bootstrap.proto#envoy-v3-api-msg-config-bootstrap-v3-bootstrap to learn more about the syntax. If set, this is the Bootstrap configuration used for the managed Envoy Proxy fleet instead of the default Bootstrap configuration set by Envoy Gateway. Some fields within the Bootstrap that are required to communicate with the xDS Server (Envoy Gateway) and receive xDS resources from it are not configurable and will result in the EnvoyProxy resource being rejected. Backward compatibility across minor versions is not guaranteed. We strongly recommend using egctl x translate to generate a EnvoyProxy resource with the Bootstrap field set to the default Bootstrap configuration used. You can edit this configuration, and rerun egctl x translate to ensure there are no validation errors.
concurrency
integer
false
Concurrency defines the number of worker threads to run. If unset, it defaults to the number of cpuset threads on the platform.
RoutingType can be set to “Service” to use the Service Cluster IP for routing to the backend, or it can be set to “Endpoint” to use Endpoint routing. The default is “Endpoint”.
MergeGateways defines if Gateway resources should be merged onto the same Envoy Proxy Infrastructure. Setting this field to true would merge all Gateway Listeners under the parent Gateway Class. This means that the port, protocol and hostname tuple must be unique for every listener. If a duplicate listener is detected, the newer listener (based on timestamp) will be rejected and its status will be updated with a “Accepted=False” condition. Mutually exclusive with MergeBackends.
MergeBackends configures cluster deduplication: routes that reference the same backend share a single Envoy cluster instead of Envoy Gateway generating one cluster per route rule. This reduces xDS size, active health-check traffic, and stats cardinality, and improves upstream connection pooling. Only a route’s own backendRefs (HTTPRoute, GRPCRoute, TLSRoute, TCPRoute, UDPRoute) are considered. A backend used any other way, such as a RequestMirror filter or an external service of a SecurityPolicy or EnvoyExtensionPolicy, is never merged. A BackendTrafficPolicy that targets a backend only reports status for Gateways where the backend is used as a route backendRef. Disabled when unset; specifying this field at all (even without further configuration) enables it. Mutually exclusive with MergeGateways.
FilterOrder defines the order of filters in the Envoy proxy’s HTTP filter chain. The FilterPosition in the list will be applied in the order they are defined. If unspecified, the default filter order is applied. Default filter order is: - envoy.filters.http.custom_response - envoy.filters.http.health_check - envoy.filters.http.fault - envoy.filters.http.cors - envoy.filters.http.header_mutation - envoy.filters.http.ext_authz - envoy.filters.http.api_key_auth - envoy.filters.http.basic_auth - envoy.filters.http.oauth2 - envoy.filters.http.jwt_authn - envoy.filters.http.stateful_session - envoy.filters.http.buffer - envoy.filters.http.lua - envoy.filters.http.ext_proc - envoy.filters.http.wasm - envoy.filters.http.dynamic_modules - envoy.filters.http.geoip - envoy.filters.http.rbac - envoy.filters.http.local_ratelimit - envoy.filters.http.ratelimit - envoy.filters.http.bandwidth_limit - envoy.filters.http.grpc_web - envoy.filters.http.grpc_json_transcoder - envoy.filters.http.grpc_stats - envoy.filters.http.credential_injector - envoy.filters.http.compressor - envoy.filters.http.dynamic_forward_proxy - envoy.filters.http.alternate_protocols_cache - envoy.filters.http.router Note: “envoy.filters.http.router” cannot be reordered, it’s always the last filter in the chain.
BackendTLS is the TLS configuration for the Envoy proxy to use when connecting to backends. These settings are applied on backends for which TLS policies are specified.
IPFamily specifies the IP family for the EnvoyProxy fleet. This setting only affects the Gateway listener port and does not impact other aspects of the Envoy proxy configuration. If not specified, the system will operate as follows: - It defaults to IPv4 only. - IPv6 and dual-stack environments are not supported in this default configuration. Note: To enable IPv6 or dual-stack functionality, explicit configuration is required.
LuaValidation determines strictness of the Lua script validation for Lua EnvoyExtensionPolicies Default: Strict Deprecated: Use Lua.ValidationType instead. This field will be removed in a future release.
Lua configures how Lua scripts from EnvoyExtensionPolicy resources are validated in the gateway controller. It selects the validation mode and, for the Strict mode, defines the filesystem paths and environment variables the scripts are permitted to access during validation.
DynamicModules defines the set of dynamic modules that are allowed to be used by EnvoyExtensionPolicy resources and dynamic module load balancer policies. Each entry registers a module by a logical name and specifies the shared library that Envoy will load. The EnvoyProxy owner is responsible for ensuring the module .so files are available on the proxy container’s filesystem (e.g., via init containers, custom images, or shared volumes).
WasmModules defines the set of Wasm modules that are allowed to be used by EnvoyExtensionPolicy resources. Each entry registers a module by a logical name and a source (currently Local path). When EnvoyExtensionPolicy.wasm[].code is omitted, wasm[].name is looked up in this list. The EnvoyProxy owner is responsible for ensuring Local modules are available on the proxy container’s filesystem (e.g., via init containers, custom images, or shared volumes). EnvoyExtensionPolicy never carries a raw filesystem path.
MergeType controls how this EnvoyProxy merges with less specific configurations in the hierarchy (EnvoyGateway defaults < GatewayClass < Gateway). If unset, this EnvoyProxy completely replaces less specific settings. Note: this field has no effect when set in EnvoyGateway’s default EnvoyProxySpec.
EnvoyProxyStatus
EnvoyProxyStatus defines the observed state of EnvoyProxy.
HTTP defines the HTTP External Authorization service. Either GRPCService or HTTPService must be specified, and only one of them can be provided.
headersToExtAuth
string array
false
HeadersToExtAuth defines the client request headers that will be included in the request to the external authorization service. Note: If not specified, the default behavior for gRPC and HTTP external authorization services is different due to backward compatibility reasons. All headers will be included in the check request to a gRPC authorization server. Only the following headers will be included in the check request to an HTTP authorization server: Host, Method, Path, Content-Length, and Authorization. And these headers will always be included to the check request to an HTTP authorization server by default, no matter whether they are specified in HeadersToExtAuth or not.
Timeout defines the timeout for requests to the external authorization service. If not specified, defaults to 10 seconds.
failOpen
boolean
false
false
FailOpen is a switch used to control the behavior when a response from the External Authorization service cannot be obtained. If FailOpen is set to true, the system allows the traffic to pass through. Otherwise, if it is set to false or not set (defaulting to false), the system blocks the traffic and returns a HTTP 5xx error, reflecting a fail-closed approach. This setting determines whether to prioritize accessibility over strict security in case of authorization service failure. If set to true, the External Authorization will also be bypassed if its configuration is invalid.
recomputeRoute
boolean
false
RecomputeRoute clears the route cache and recalculates the routing decision. This field must be enabled if the headers added or modified by the ExtAuth are used for route matching decisions. If the recomputation selects a new route, features targeting the new matched route will be applied.
includeRouteMetadata
boolean
false
IncludeRouteMetadata sends Envoy Gateway’s built-in route metadata to the external authorization service as context. This includes Envoy Gateway’s built-in metadata for the selected route in the “envoy-gateway” metadata namespace. The metadata is exposed under the “resources” field as a list of route resource objects. For example: envoy-gateway: resources: - kind: HTTPRoute name: backend namespace: default annotations: foo: bar The resource object may include fields such as kind, namespace, name, sectionName, and supported route annotations.
ContextExtensions are analogous to http_request.headers, however these contents will not be sent to the upstream server. This provides an extension mechanism for sending additional information to the auth server without modifying the proto definition. It maps to the internal opaque context in the filter chain.
statusOnError
integer
false
Sets the HTTP status that is returned when the authorization service returns an error or cannot be reached. Defaults to 403 Forbidden. Only 4xx and 5xx status codes are supported.
ExtProc
ExtProc defines the configuration for External Processing filter.
BackendRef references a Kubernetes object that represents the backend server to which the authorization request will be sent. Deprecated: Use BackendRefs instead. This field will be removed in v1.11.
MessageTimeout is the timeout for a response to be returned from the external processor Default: 200ms
failOpen
boolean
false
false
FailOpen is a switch used to control the behavior when failing to call the external processor. If FailOpen is set to true, the system bypasses the ExtProc extension and allows the traffic to pass through. If it is set to false or not set (defaulting to false), the system blocks the traffic and returns an HTTP 5xx error. If set to true, the ExtProc extension will also be bypassed if the configuration is invalid.
ProcessingMode defines how request and response body is processed Default: header and body are not sent to the external processor
shadowMode
boolean
false
ShadowMode sets if envoy gateway should treat this external processor as “send and go”. When enabled, Envoy forwards request/response data to the external processor but does not wait for or apply any response from it. This maps to Envoy’s observability_mode on the ext_proc filter. Defaults to false.
Refer to Kubernetes API documentation for fields of metadata.
statusOnError
integer
false
Sets the HTTP status that is returned to the client when the external processor returns an error or cannot be reached. Defaults to 500 Internal Server Error. Only 4xx and 5xx status codes are supported.
StreamedExtProcBodyProcessingMode will stream the body to the server in pieces as they arrive at the proxy.
Buffered
BufferedExtProcBodyProcessingMode will buffer the message body in memory and send the entire body at once. If the body exceeds the configured buffer limit, then the downstream system will receive an error.
BufferedPartialExtBodyHeaderProcessingMode will buffer the message body in memory and send the entire body in one chunk. If the body exceeds the configured buffer limit, then the body contents up to the buffer limit will be sent.
ExtProcMetadata
ExtProcMetadata defines options related to the sending and receiving of dynamic metadata to and from the
external processor service
Defines processing mode for responses. If present, response headers are sent. Response body is processed according to the specified mode.
allowModeOverride
boolean
false
AllowModeOverride allows the external processor to override the processing mode set via the mode_override field in the gRPC response message. This defaults to false.
ExtensionAPISettings
ExtensionAPISettings defines the settings specific to Gateway API Extensions.
EnableEnvoyPatchPolicy enables Envoy Gateway to reconcile and implement the EnvoyPatchPolicy resources. Warning: Enabling EnvoyPatchPolicy may lead to complete security compromise of your system. Users with EnvoyPatchPolicy permissions can inject arbitrary configuration to proxies, leading to high Confidentiality, Integrity and Availability risks.
enableBackend
boolean
true
EnableBackend enables Envoy Gateway to reconcile and implement the Backend resources.
enableExtensionBackends
boolean
false
EnableExtensionBackends enables HTTP callout backend bindings declared in EnvoyExtensionPolicy for Lua, Wasm and dynamic modules. Disabled by default. Backend resources also require EnableBackend. Bindings can add destinations that Envoy contacts using its network access and any client certificate selected by the backend TLS configuration.
disableLua
boolean
false
DisableLua determines if Lua EnvoyExtensionPolicies should be disabled. If set to true, the Lua EnvoyExtensionPolicy feature will be disabled. This field is mutually exclusive with EnableLua. Deprecated: Use EnableLua instead. This field will be removed in a future release.
enableLua
boolean
false
EnableLua enables the Lua EnvoyExtensionPolicy feature. If set to true, the Lua EnvoyExtensionPolicy feature will be enabled. By default, Lua policies are disabled. This field is mutually exclusive with DisableLua.
enableSDSSecretRef
boolean
true
EnableSDSSecretRef enables read SDS(Secret Discovery Service) settings from a secret(with type gateway.envoyproxy.io/sds).
ExtensionBackend
ExtensionBackend binds an extension’s backend alias to a backend resource.
BackendRef references the backend for HTTP callouts. References to another namespace require a ReferenceGrant allowing the policy that declares this binding.
BackendSettings configures connections and traffic for this binding’s cluster. Request timeouts and retries are controlled by the extension’s callout API. RequestTimeout and StreamIdleTimeout are not supported here. DynamicModule load balancing is not supported here. HTTP3 is not supported for extension backends.
ExtensionHooks
ExtensionHooks defines extension hooks across all supported runners
Name is a unique identifier for this extension manager. Required when using the plural ExtensionManagers field. Used for logging, metrics, and error identification.
PolicyResources defines the set of K8S resources the extension server will handle as directly attached Gateway API policies. Only policies in the same namespace as the target Gateway resources are supported. Cross-namespace attachments are not supported.
BackendResources defines the set of K8s resources the extension will handle as custom backendRef resources. These resources can be referenced in HTTPRoute backendRefs to enable support for custom backend types (e.g., S3, Lambda, etc.) that are not natively supported by Envoy Gateway. The backend kinds Envoy Gateway resolves itself (core Service, multicluster.x-k8s.io/ServiceImport and gateway.envoyproxy.io/Backend) are not allowed: backendRefs are matched by group and kind, so listing one of them would hand every backendRef of that kind in the cluster to the extension, bypassing Envoy Gateway’s own validation and endpoint resolution for it. Use the xDS translator hooks to adjust the clusters Envoy Gateway generates for those backends instead.
SecretResources defines the set of K8s resources the extension will handle as secret sources. These resources can be referenced in place of a Kubernetes Secret by group and kind, allowing Envoy to use a secret held by an external provider. Currently this covers a Gateway or ListenerSet listener’s tls.certificateRefs; other secret consumers may be added over time.
Service defines the configuration of the extension service that the Envoy Gateway Control Plane will call through extension hooks.
failOpen
boolean
false
FailOpen defines if Envoy Gateway should ignore errors returned from the Extension Service hooks. When set to false, Envoy Gateway does not ignore extension Service hook errors. As a result, xDS updates are skipped for the relevant envoy proxy fleet and the previous state is preserved. When set to true, if the Extension Service hooks return an error, no changes will be applied to the source of the configuration which was sent to the extension server. The errors are ignored and the resulting xDS configuration is updated in the xDS snapshot. FailOpen does not apply to the Secret hook: its errors are never ignored. Default: false
Zone defines the service zone of the backend endpoint.
host
string
false
Host define the extension service hostname. Deprecated: use the appropriate transport attribute instead (FQDN,IP,Unix). This field will be removed in v1.11.
port
integer
false
80
Port defines the port the extension service is exposed on. Deprecated: use the appropriate transport attribute instead (FQDN,IP,Unix). This field will be removed in v1.11.
Timeout is the maximum duration of a single call to the extension service, including the time spent waiting for the connection to become ready and any retries. When the timeout is exceeded the call fails with DEADLINE_EXCEEDED, which lets ExtensionManager.FailOpen take effect when the extension service is unreachable. If unset, calls have no deadline and block until the extension service becomes reachable.
ExtensionServiceRetry
ExtensionServiceRetry defines the retry policy for to use when errors are encountered in communication with the extension service.
CertificateRef is a reference to a Kubernetes Secret with a CA certificate in a key named “tls.crt”. The CA certificate is used by Envoy Gateway to verify the server certificate presented by the extension server.
ClientCertificateRef is a reference to a Kubernetes Secret with a client certificate and key for client certificate authentication (mTLS). The secret must contain both “tls.crt” and “tls.key” keys. When specified, Envoy Gateway will present this client certificate to the extension server for mTLS authentication. If not specified, only server certificate validation is performed.
ExtractFrom
ExtractFrom is where to fetch the key from the coming request.
Only one of headers, params or cookies must be specified.
Headers is the names of the header to fetch the key from. If multiple headers are specified, envoy will look for the api key in the order of the list. This field is optional, but only one of headers, params or cookies must be specified.
params
string array
false
Params is the names of the query parameter to fetch the key from. If multiple params are specified, envoy will look for the api key in the order of the list. This field is optional, but only one of headers, params or cookies must be specified.
cookies
string array
false
Cookies is the names of the cookie to fetch the key from. If multiple cookies are specified, envoy will look for the api key in the order of the list. This field is optional, but only one of headers, params or cookies must be specified.
Hostname defines the FQDN hostname of the backend endpoint.
port
integer
true
Port defines the port of the backend endpoint.
FaultInjection
FaultInjection defines the fault injection policy to be applied. This configuration can be used to
inject delays and abort requests to mimic failure scenarios such as service failures and overloads
After defines the filter that should come after the filter. Only one of Before or After must be set.
ForceLocalZone
ForceLocalZone defines override configuration for forcing all traffic to stay within the local zone instead of the default behavior
which maintains equal distribution among upstream endpoints while sending as much traffic as possible locally.
MinEndpointsInZoneThreshold is the minimum number of upstream endpoints in the local zone required to honor the forceLocalZone override. This is useful for protecting zones with fewer endpoints.
ForwardProtoConfig
ForwardProtoConfig configures the ports used to infer the x-forwarded-proto
header from the PROXY protocol destination port. When the restored local address
(populated by the PROXY protocol listener filter) has a destination port matching
one of these lists, the x-forwarded-proto header is set to the corresponding scheme.
At least one of httpsDestinationPorts or httpDestinationPorts must be set.
HTTPSDestinationPorts are the destination ports treated as HTTPS. When the PROXY protocol destination port matches one of these, the x-forwarded-proto header is set to “https”. Common values: 443, 8443.
httpDestinationPorts
integer array
false
HTTPDestinationPorts are the destination ports treated as HTTP. When the PROXY protocol destination port matches one of these, the x-forwarded-proto header is set to “http”. Common values: 80, 8080.
GRPCActiveHealthChecker
GRPCActiveHealthChecker defines the settings of the GRPC health check.
Service to send in the health check request. If this is not specified, then the health check request applies to the entire server and not to a specific service.
hostname
string
false
Hostname defines the value of the :authority header sent with active gRPC health checks. Authority selection uses this order: this field, the associated Backend endpoint hostname if available, then the effective Route hostname. If none of them is set, Envoy falls back to the name of the cluster, which is not a valid authority and is rejected by some gRPC servers.
BackendRef references a Kubernetes object that represents the backend server to which the authorization request will be sent. Deprecated: Use BackendRefs instead. This field will be removed in v1.11.
ProtoDescriptor defines where to find the protobuf descriptor set of the gRPC services.
services
string array
false
Services defines the gRPC services to transcode. If not specified, all the services defined in the descriptor are transcoded, except the ones that come from imported files.
PrintOptions defines how the gRPC response is printed as JSON.
ignoreUnknownQueryParameters
boolean
false
IgnoreUnknownQueryParameters ignores the query parameters that can’t be mapped to a field of the gRPC request. If false, a request with such a parameter is not transcoded and is sent to the backend as is.
convertGRPCStatus
boolean
false
ConvertGRPCStatus converts the gRPC status of an error response to the HTTP status code and a JSON body.
GRPCSettings
GRPCSettings provides gRPC configuration for listeners.
EnableWeb configures the gRPC-web filter on the listener. The gRPC-web filter allows clients (typically browsers) to make gRPC calls using HTTP/1.1 or HTTP/2. This is enabled by default for GRPCRoute and opt-in for HTTPRoute. In general, gRPC traffic should be handled via GRPCRoute, but there are cases where users want to route gRPC using HTTPRoute for its richer matching capabilities. Therefore, we enable this behavior only when it is explicitly opted in.
GatewayAPISettings provides a mechanism to opt into experimental Gateway API resources.
These APIs are experimental today and are subject to change or removal as they mature.
GeoIPAnonymousMatch matches anonymous network signals emitted by the GeoIP provider.
If multiple fields are specified, all specified fields must match.
These signals are not mutually exclusive. A single IP may satisfy multiple
flags at the same time (for example, a commercial VPN exit IP may also be
classified as a public proxy, so both IsVPN and IsProxy can be true).
GeoIPMaxMind configures the MaxMind provider.
These database files are expected to be mounted into the Envoy container, and a sidecar container can be used to update the database files.
Rules are a list of RateLimit selectors and limits. Each rule and its associated limit is applied in a mutually exclusive way. If a request matches multiple rules, each of their associated limits get applied, so a single request might increase the rate limit counters for multiple rules if selected. The rate limit service will return a logical OR of the individual rate limit decisions of all matching rules. For example, if a request matches two rules, one rate limited and one not, the final decision will be to rate limit the request.
GroupVersionKind
GroupVersionKind unambiguously identifies a Kind.
It can be converted to k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind
CompressionLevel sets the zlib compression level, from 1 (fastest compression, lowest compression ratio) to 9 (slowest compression, best compression ratio). If not set, Envoy uses the zlib default level, which is equivalent to level 6.
CompressionStrategy selects the zlib compression strategy, which is directly related to the characteristics of the content. Most of the time “Default” is the best choice. If not set, defaults to Default.
memoryLevel
integer
false
MemoryLevel controls the amount of internal memory used by zlib, from 1 to 9. Higher values use more memory, but are faster and produce better compression results. If not set, defaults to 5.
windowBits
integer
false
WindowBits represents the base two logarithm of the compressor’s window size, from 9 to 15. Larger window results in better compression at the expense of memory usage. If not set, defaults to 12, which will produce a 4096 bytes window.
chunkSize
integer
false
ChunkSize is the size in bytes of zlib’s next output buffer, from 4096 to 65536. If not set, defaults to 4096.
HTTP10Settings
HTTP10Settings provides HTTP/1.0 configuration on the listener.
UseDefaultHost specifies whether a default Host header should be injected into HTTP/1.0 requests that do not include one. When set to true, Envoy Gateway injects the hostname associated with the listener or route into the request, in the following order: 1. If the targeted listener has a non-wildcard hostname, use that hostname. 2. If there is exactly one HTTPRoute with a non-wildcard hostname under the targeted listener, use that hostname. Note: Setting this field to true without a non-wildcard hostname makes the ClientTrafficPolicy invalid.
HTTP1Settings
HTTP1Settings provides HTTP/1 configuration on the listener.
EnableTrailers defines if HTTP/1 trailers should be proxied by Envoy. Note: this field currently configures both the client connection and the backend HTTP/1 protocol settings. In a future release it will be restricted to the client connection only. Use BackendTrafficPolicy.http1.enableTrailers for backend settings. Enable the EnvoyGateway runtimeFlag ApplyClientTrafficPolicyHTTP1SettingsToClientsOnly to opt in to the new behavior now.
preserveHeaderCase
boolean
false
PreserveHeaderCase defines if Envoy should preserve the letter case of headers. By default, Envoy will lowercase all the headers. Note: this field currently configures both the client connection and the backend HTTP/1 protocol settings. In a future release it will be restricted to the client connection only. Use BackendTrafficPolicy.http1.preserveHeaderCase for backend settings. Enable the EnvoyGateway runtimeFlag ApplyClientTrafficPolicyHTTP1SettingsToClientsOnly to opt in to the new behavior now.
HTTP10 turns on support for HTTP/1.0 and HTTP/0.9 requests. Note: this field currently forces explicit HTTP/1 for backend connections when other backend-relevant HTTP/1 fields like EnableTrailers and PreserveHeaderCase are absent. In a future release it will no longer force explicit HTTP/1 on backend connections. Use BackendTrafficPolicy.http1: {} to force HTTP/1 on a backend cluster explicitly.
disableSafeMaxConnectionDuration
boolean
false
DisableSafeMaxConnectionDuration controls the close behavior for HTTP/1 connections. By default, connection closure is delayed until the next request arrives after maxConnectionDuration is exceeded. It then adds a Connection: close header and gracefully closes the connection after the response completes. When set to true (disabled), Envoy uses its default drain behavior, closing the connection shortly after maxConnectionDuration elapses. Has no effect unless maxConnectionDuration is set.
IgnoredUpgradeTypes specifies a list of upgrade types for which HTTP/1.1 Upgrade requests should be ignored by Envoy instead of being rejected with a 403 response. When a client sends an HTTP/1.1 request with Connection: Upgrade and an Upgrade header matching one of these matchers, Envoy will strip the upgrade headers and process the request as a normal HTTP/1.1 request. Example: To ignore TLS upgrade requests (RFC 2817), use a Prefix match with value “TLS/”.
AdvertisedPort specifies the port advertised to clients in the HTTP/3 alt-svc response header. It does not change the listener or Service port. If unset, the Gateway listener port is advertised.
HTTPActiveHealthChecker
HTTPActiveHealthChecker defines the settings of http health check.
Hostname defines the HTTP Host header used for active HTTP health checks. Host selection uses this order: this field, the associated Backend endpoint hostname if available, then the effective Route hostname.
path
string
true
Path defines the HTTP path that will be requested during health checking.
Protocol is the HTTP protocol that active health check requests are sent with. Defaults to Auto, which uses the same protocol as regular requests to the backend: - HTTP2 for a backend configured for HTTP/2, through a kubernetes.io/h2c, gateway.envoyproxy.io/h2c or grpc appProtocol, or as the backend of a GRPCRoute. - The protocol negotiated through ALPN for a TLS backend that negotiates it, with HTTP1 as the fallback when nothing is negotiated. - HTTP1 otherwise. Set HTTP1 or HTTP2 when the health check endpoint speaks a different protocol than the application, for example a backend that serves HTTP/1.1 traffic but only accepts HTTP/2 health checks. An explicit protocol is always used as is.
method
string
false
Method defines the HTTP method used for health checking. Defaults to GET
RetriableStatuses defines a list of HTTP response statuses considered retriable. Responses matching these statuses count towards the unhealthy threshold but do not result in the host being considered immediately unhealthy. The expected statuses take precedence for any range overlaps with this field.
RequestReceivedTimeout is the duration envoy waits for the complete request reception. This timer starts upon request initiation and stops when either the last byte of the request is sent upstream or when the response begins.
RequestHeadersReceivedTimeout is the duration envoy waits for the request headers to arrive. The timer is activated when the first byte of the headers is received, and is disarmed when the last byte of the headers has been received. If not specified or set to 0, this timeout is disabled.
Type specifies how to match against the value of the cookie.
name
string
true
Name is the cookie name to evaluate.
value
string
true
Value is the cookie value to be matched.
HTTPCredentialInjectionFilter
HTTPCredentialInjectionFilter defines the configuration to inject credentials into the request.
This is useful when the backend service requires credentials in the request, and the original
request does not contain them. The filter can inject credentials into the request before forwarding
it to the backend service.
Status Code of the HTTP response If unset, defaults to 200. Note: when this filter is referenced from a GRPCRoute, a 2xx status code (including the default 200) is rejected; a non-2xx status code must be set.
BackendRef references a Kubernetes object that represents the backend server to which the authorization request will be sent. Deprecated: Use BackendRefs instead. This field will be removed in v1.11.
BackendSettings holds configuration for managing the connection to the backend.
path
string
false
Path is the path of the HTTP External Authorization service. If path is specified, the authorization request will be sent to that path, or else the authorization request will use the path of the original request. Please note that the original request path will be appended to the path specified here. For example, if the original request path is “/hello”, and the path specified here is “/auth”, then the path of the authorization request will be “/auth/hello”. If the path is not specified, the path of the authorization request will be “/hello”. Only one of Path or PathOverride can be set.
pathOverride
string
false
PathOverride replaces the original request path in the authorization request. If set, the path will be overridden to this value during authorization. For example, if the original request path is “/hello”, and PathOverride is set to “/auth”, then the path of the authorization request will be “/auth”. Only one of Path or PathOverride can be set.
headersToBackend
string array
false
HeadersToBackend are the authorization response headers that will be added to the original client request before sending it to the backend server. Note that coexisting headers will be overridden. If not specified, no authorization response headers will be added to the original client request.
HTTPHeaderFilter
HTTPHeaderFilter defines a filter that modifies the headers of an HTTP
request or response.
The Set, Add, AddIfAbsent, Remove and RemoveOnMatch fields permit only one
action for a given header name. Specifying multiple actions of the same or
different type for any one header name via those fields is invalid, and
configuration to set or add multiple values for a header must use RFC 7230
header value formatting, separating each value with a comma.
The Mutations field has no such restriction. It is an ordered list, so the
same header name may appear in any number of operations and each one is
applied in turn.
Mutations is an ordered list of header operations that are applied in exactly the order specified. Use this field when the sequence of operations matters, for example setting a header and then appending to it, or removing a header and then re-adding it. Mutations are always applied FIRST, in list order. The Set, Add, AddIfAbsent, Remove and RemoveOnMatch fields below are then applied after the mutations, preserving their existing ordering (Add, then Set, then AddIfAbsent, then Remove, then RemoveOnMatch).
Set overwrites the request with the given header (name, value) before the action. Input: GET /foo HTTP/1.1 my-header: foo Config: set: - name: “my-header” value: “bar” Output: GET /foo HTTP/1.1 my-header: bar
Add adds the given header(s) (name, value) to the request before the action. It appends to any existing values associated with the header name. Input: GET /foo HTTP/1.1 my-header: foo Config: add: - name: “my-header” value: “bar,baz” Output: GET /foo HTTP/1.1 my-header: foo,bar,baz
AddIfAbsent adds the given header(s) (name, value) to the request/response only if the header does not already exist. Unlike Add which appends to existing values, this is a no-op if the header is already present. Input: GET /foo HTTP/1.1 my-header: foo Config: addIfAbsent: - name: “my-header” value: “bar” Output: GET /foo HTTP/1.1 my-header: foo
remove
string array
false
Remove the given header(s) from the HTTP request before the action. The value of Remove is a list of HTTP header names. Note that the header names are case-insensitive (see https://datatracker.ietf.org/doc/html/rfc2616#section-4.2). Input: GET /foo HTTP/1.1 my-header1: foo my-header2: bar my-header3: baz Config: remove: [“my-header1”, “my-header3”] Output: GET /foo HTTP/1.1 my-header2: bar
RemoveOnMatch removes every header whose name matches the specified string matcher. Matching is performed on the header name (case-insensitive).
HTTPHeaderWrite
HTTPHeaderWrite defines a header to write and how it should be applied when a
header with the same name already exists. It mirrors Envoy’s
core.v3.HeaderValueOption.
Action controls how the header value is written when a header with the same name already exists. Defaults to Add.
keepEmptyValue
boolean
false
KeepEmptyValue controls whether the header is still written when its value is empty. This matters for values produced by substitution formatters, e.g. “%REQ(x-foo)%”, which may resolve to an empty string at request time. Envoy drops such headers by default; set this to true to keep them with an empty value. When unset, it defaults to true only if the configured value itself is the empty string, so a literal empty header is always written.
HTTPHealthCheckProtocol
Underlying type:string
HTTPHealthCheckProtocol specifies the HTTP protocol used to send active HTTP
health check requests to the backend.
PathRegex defines a regex match and substitution applied to the request path to compute the rewritten Host header. For example, with: pathRegex: pattern: “^/tenant/([a-z0-9-]+)/.*" substitution: “\1.example.internal” a request to “http://foo.bar.com/tenant/tenant1/api/v1" has its upstream Host header rewritten to “tenant1.example.internal” (the request path “/tenant/tenant1/api/v1” is preserved).
HTTPHostnameModifierType
Underlying type:string
HTTPPathModifierType defines the type of Hostname rewrite.
ReplaceRegexMatch defines a path regex rewrite. The path portions matched by the regex pattern are replaced by the defined substitution. https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/route/v3/route_components.proto#envoy-v3-api-field-config-route-v3-routeaction-regex-rewrite Some examples: (1) replaceRegexMatch: pattern: ^/service/([^/]+)(/.)$ substitution: \2/instance/\1 Would transform /service/foo/v1/api into /v1/api/instance/foo. (2) replaceRegexMatch: pattern: one substitution: two Would transform /xxx/one/yyy/one/zzz into /xxx/two/yyy/two/zzz. (3) replaceRegexMatch: pattern: ^(.?)one(.*)$ substitution: \1two\2 Would transform /xxx/one/yyy/one/zzz into /xxx/two/yyy/one/zzz. (3) replaceRegexMatch: pattern: (?i)/xxx/ substitution: /yyy/ Would transform path /aaa/XxX/bbb into /aaa/yyy/bbb (case-insensitive).
HTTPPathModifierType
Underlying type:string
HTTPPathModifierType defines the type of path redirect or rewrite.
Hostname defines the configuration to rewrite the Host header for mirrored requests.
HTTPRouteFilter
HTTPRouteFilter is a custom Envoy Gateway HTTPRouteFilter which provides extended
traffic processing options such as path regex rewrite, direct response and more.
DirectResponse returns a fixed response for matching requests. When this filter is referenced from a GRPCRoute, only a non-2xx status code is supported. gRPC signals success with a grpc-status trailer and a response message, which a direct response cannot produce, so a 2xx status code (which maps to the gRPC OK status) yields an invalid response for gRPC clients. Use a non-2xx status code to deny or block gRPC requests (e.g. 403 maps to PERMISSION_DENIED, 404 to UNIMPLEMENTED, 429/503 to UNAVAILABLE).
RequestMirror defines configuration for request mirroring modifiers. This configuration works together with the Gateway API RequestMirror filter on the attached HTTPRoute rule.
GRPCJSONTranscoder converts a JSON/HTTP request to a gRPC request, and the gRPC response back to JSON. It can only be used in the rule filters of an HTTPRoute. It is not supported in a GRPCRoute or in the filters of a backendRef.
Matches defines additional matching criteria for the HTTPRoute rule. As with HTTPRouteRule.Matches, the rule is matched if any one match applies. When both HTTPRouteRule.Matches and HTTPRouteFilter.Matches are set, the effective matching is the logical AND of the two sets.
backendPriority
integer
false
BackendPriority sets the Envoy locality priority of the endpoints belonging to the backendRef this filter is attached to, enabling priority-based failover between the backendRefs of a single route rule. 0 is the highest priority. Envoy sends traffic to the lowest priority value that has enough healthy endpoints, and only spills over to the next value as that health degrades. It is highly recommended to configure active or passive health checks so that failover can be detected when the higher priority backends become unhealthy. This overrides the priority derived from the referenced Backend’s fallback field. For additional details, see https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/load_balancing/priority This filter is only valid when referenced from a backendRef’s filters. Referencing it from a route rule’s filters is rejected: a rule-level filter applies uniformly to every backendRef of the rule, and a uniform priority carries no failover meaning.
HTTPRouteMatchFilter
HTTPRouteMatchFilter defines additional matching criteria for the HTTPRoute rule.
At least one matcher must be specified.
MaxStreamDuration is the maximum duration for a stream to complete. This timeout measures the time from when the request is sent until the response stream is fully consumed and does not apply to non-streaming requests. When set to “0s”, no max duration is applied and streams can run indefinitely.
The stream idle timeout defines the amount of time a stream can exist without any upstream or downstream activity. If not specified, StreamIdleTimeout is inherited from the listener-level setting, which can be configured via ClientTrafficPolicy.
HTTPURLRewriteFilter
HTTPURLRewriteFilter define rewrites of HTTP URL components such as path and host
AppendXForwardedHost controls whether the original Host header value is appended to the X-Forwarded-Host header when hostname rewriting is configured. Defaults to true for backward compatibility.
HTTPWasmCodeSource
HTTPWasmCodeSource defines the HTTP URL containing the Wasm code.
SHA256 checksum that will be used to verify the Wasm code. If not specified, Envoy Gateway will not verify the downloaded Wasm code. kubebuilder:validation:Pattern=^[a-f0-9]\{64\}$
Type specifies how to match against the value of the header.
name
string
true
Name of the HTTP header. The header name is case-insensitive unless PreserveHeaderCase is set to true. For example, “Foo” and “foo” are considered the same header.
value
string
false
Value within the HTTP header. Do not set this field when Type=“Distinct”, implying matching on any/all unique values within the header.
invert
boolean
false
false
Invert specifies whether the value match result will be inverted. Do not set this field when Type=“Distinct”, implying matching on any/all unique values within the header.
HeaderMatchType
Underlying type:string
HeaderMatchType specifies the semantics of how HTTP header values should be compared.
Valid HeaderMatchType values are “Exact”, “RegularExpression”, and “Distinct”.
HeaderMatchExact matches the exact value of the Value field against the value of the specified HTTP Header.
RegularExpression
HeaderMatchRegularExpression matches a regular expression against the value of the specified HTTP Header. The regex string must adhere to the syntax documented in https://github.com/google/re2/wiki/Syntax.
Distinct
HeaderMatchDistinct matches any and all possible unique values encountered in the specified HTTP Header. Note that each unique value will receive its own rate limit bucket.
HeaderSettings
HeaderSettings provides configuration options for headers on the listener.
XForwardedClientCert configures how Envoy Proxy handle the x-forwarded-client-cert (XFCC) HTTP header. x-forwarded-client-cert (XFCC) is an HTTP header used to forward the certificate information of part or all of the clients or proxies that a request has flowed through, on its way from the client to the server. Envoy proxy may choose to sanitize/append/forward the XFCC header before proxying the request. If not set, the default behavior is sanitizing the XFCC header.
WithUnderscoresAction configures the action to take when an HTTP header with underscores is encountered. The default action is to reject the request.
preserveXRequestID
boolean
false
PreserveXRequestID configures Envoy to keep the X-Request-ID header if passed for a request that is edge (Edge request is the request from external clients to front Envoy) and not reset it, which is the current Envoy behaviour. Defaults to false and cannot be combined with RequestID. Deprecated: use RequestID=PreserveOrGenerate instead. This field will be removed in v1.11.
RequestID configures Envoy’s behavior for handling the X-Request-ID header. When omitted default behavior is Generate which builds the X-Request-ID for every request and ignores pre-existing values from the edge. (An “edge request” refers to a request from an external client to the Envoy entrypoint.)
MaxRequestHeaderLimit provides configuration for the maximum size of the request headers allowed for incoming connections, mapping to the Envoy max_request_headers_kb HTTP connection manager setting. Requests whose headers exceed this limit receive a 431 (Request Header Fields Too Large) response. The value is rounded up to the nearest KiB, must be at least 1Ki, and cannot exceed 8192Ki (the maximum Envoy supports). For example, 60Ki, 96Ki, 128Ki etc. Note that when the suffix is not provided, the value is interpreted as bytes. Default: 60Ki bytes.
HeaderWriteAction
Underlying type:string
HeaderWriteAction controls how a header value is written when a header with
the same name already exists. The names match the Add, Set and AddIfAbsent
fields of HTTPHeaderFilter.
When number of unhealthy endpoints for a backend reaches this threshold Envoy will disregard health status and balance across all endpoints. It’s designed to prevent a situation in which host failures cascade throughout the cluster as load increases. If not set, the default value is 50%. To disable panic mode, set value to 0.
HealthCheckOverrides
HealthCheckOverrides allows overriding default health check behavior for specific use cases.
Port overrides the health check port. If not set, the endpoint’s serving port is used for health checks. This is useful when health checks are served on a different port than the main service port (e.g., port 443 for service, port 9090 for health checks).
HealthCheckSettings
HealthCheckSettings provides HealthCheck configuration on the HTTP/HTTPS listener.
StripTrailingHostDot determines if the trailing dot of the host should be removed from the Host/Authority header before any processing of the request. This affects the upstream host header as well. Without this option, incoming requests with host “example.com.” will not match routes with domains set to “example.com”. When the host includes a port (for example “example.com.:443”), only the trailing dot from the host section is stripped, leaving the port as-is (“example.com:443”). Defaults to false.
HostnamePathRegexRewrite
HostnamePathRegexRewrite defines a hostname rewrite computed from the request path using regex.
Pattern matches a regular expression against the value of the HTTP Path. The regex string must adhere to the syntax documented in https://github.com/google/re2/wiki/Syntax.
substitution
string
true
Substitution is an expression that replaces the matched portion. The expression may include numbered capture groups that adhere to syntax documented in https://github.com/google/re2/wiki/Syntax. The resulting value is used as the upstream Host header and should be constrained to a valid DNS hostname by using explicit regex capture groups in Pattern. The NUL, CR, and LF characters are not allowed: they are invalid in an HTTP header value and are rejected by the Envoy proto (well_known_regex HTTP_HEADER_VALUE), which would otherwise cause the generated configuration to be rejected by the data plane.
DualStack defines the dual-stack family. When set to DualStack, Envoy proxy will listen on both IPv4 and IPv6 addresses for incoming client traffic, enabling support for both IP protocol versions.
PreferDualStack
PreferDualStack defines the dual-stack family, degrading to the single family the cluster provides instead of failing when the cluster is not dual-stack.
ImagePullPolicy
Underlying type:string
ImagePullPolicy defines the policy to use when pulling an OIC image.
ImagePullPolicyIfNotPresent will only pull the image if it does not already exist in the EG cache.
Always
ImagePullPolicyAlways will pull the image when the EnvoyExtension resource version changes. Note: EG does not update the Wasm module every time an Envoy proxy requests the Wasm module.
ImageWasmCodeSource
ImageWasmCodeSource defines the OCI image containing the Wasm code.
URL is the URL of the OCI image. URL can be in the format of registry/image:tag or registry/image@sha256:digest.
sha256
string
false
SHA256 checksum that will be used to verify the OCI image. It must match the digest of the OCI image. If not specified, Envoy Gateway will not verify the downloaded OCI image. kubebuilder:validation:Pattern=^[a-f0-9]\{64\}$
ValueRef is a reference to the secret containing the credentials to be injected. This is an Opaque secret. The credential should be stored in the key “credential”, and the value should be the credential to be injected. For example, for basic authentication, the value should be “Basic ”. for bearer token, the value should be “Bearer ”.
Path is a JSONPointer expression. Refer to https://datatracker.ietf.org/doc/html/rfc6901 for more details. It specifies the location of the target document/field where the operation will be performed
jsonPath
string
false
JSONPath is a JSONPath expression. Refer to https://datatracker.ietf.org/doc/rfc9535/ for more details. It produces one or more JSONPointer expressions based on the given JSON document. If no JSONPointer is found, it will result in an error. If the ‘Path’ property is also set, it will be appended to the resulting JSONPointer expressions from the JSONPath evaluation. This is useful when creating a property that does not yet exist in the JSON document. The final JSONPointer expressions specifies the locations in the target document/field where the operation will be applied.
Optional determines whether a missing JWT is acceptable, defaulting to false if not specified. Note: Even if optional is set to true, JWT authentication will still fail if an invalid JWT is presented. See FailOpen if this is necessary for your use case.
failOpen
boolean
false
FailOpen lets a request pass JWT authentication even when its JWT is missing or invalid, rather than being rejected. This helps when a header that clients use to carry a JWT may also legitimately hold a non-JWT value that the backend relies on. A valid JWT is still verified and its claims forwarded as usual; only the rejection of requests with a missing or invalid JWT is relaxed. Because this does not enforce authentication on its own, pair it with an Authorization policy when access needs to be restricted. This is broader than Optional (which tolerates a missing JWT but still rejects an invalid one) and takes precedence over it.
Name is the name of the claim. If it is a nested claim, use a dot (.) separated string as the name to represent the full path to the claim. For example, if the claim is in the “department” field in the “organization” field, the name should be “organization.department”.
ValueType is the type of the claim value. Only String and StringArray types are supported for now.
values
string array
true
Values are the values that the claim must match. If the claim is a string type, the specified value must match exactly. If the claim is a string array type, the specified value must match one of the values in the array. If multiple values are specified, one of the values must match for the rule to match.
JWTExtractor defines a custom JWT token extraction from HTTP request.
If specified, Envoy will extract the JWT token from the listed extractors (headers, cookies, or params) and validate each of them.
If any value extracted is found to be an invalid JWT, a 401 error will be returned.
Name is the HTTP header name to retrieve the token
valuePrefix
string
false
ValuePrefix is the prefix that should be stripped before extracting the token. The format would be used by Envoy like “{ValuePrefix}”. For example, “Authorization: Bearer ”, then the ValuePrefix=“Bearer " with a space at the end.
JWTPrincipal
JWTPrincipal specifies the client identity of a request based on the JWT claims and scopes.
At least one of the claims or scopes must be specified.
Claims and scopes are And-ed together if both are specified.
Provider is the name of the JWT provider that used to verify the JWT token. In order to use JWT claims for authorization, you must configure the JWT authentication with the same provider in the same SecurityPolicy, or, when mergeType is set, in the parent SecurityPolicy this policy is merged into.
Claims are the claims in a JWT token. If multiple claims are specified, all claims must match for the rule to match. For example, if there are two claims: one for the audience and one for the issuer, the rule will match only if both the audience and the issuer match.
Scopes are a special type of claim in a JWT token that represents the permissions of the client. The value of the scopes field should be a space delimited string that is expected in the scope (or scp) claim, as defined in RFC 6749: https://datatracker.ietf.org/doc/html/rfc6749#page-23. If multiple scopes are specified, all scopes must match for the rule to match.
JWTProvider
JWTProvider defines how a JSON Web Token (JWT) can be verified.
Name defines a unique name for the JWT provider. A name can have a variety of forms, including RFC1123 subdomains, RFC 1123 labels, or RFC 1035 labels.
ClaimToHeaders is a list of JWT claims that must be extracted into HTTP request headers For examples, following config: The claim must be of type; string, int, double, bool. Array type claims are not supported
recomputeRoute
boolean
false
RecomputeRoute clears the route cache and recalculates the routing decision. This field must be enabled if the headers generated from the claim are used for route matching decisions. If the recomputation selects a new route, features targeting the new matched route will be applied.
ExtractFrom defines different ways to extract the JWT token from HTTP request. If empty, it defaults to extract JWT token from the Authorization HTTP request header using Bearer schema or access_token from query parameters.
Image specifies the EnvoyProxy container image to be used including a tag, instead of the default image. This field is mutually exclusive with ImageRepository.
imageRepository
string
false
ImageRepository specifies the container image repository to be used without specifying a tag. The default tag will be used. This field is mutually exclusive with Image.
Type indicates what deployment mode to use. “ControllerNamespace” and “GatewayNamespace” are currently supported. By default, when this field is unset or empty, Envoy Gateway will deploy Envoy Proxy fleet in the Controller namespace.
KubernetesDeployModeType
Underlying type:string
KubernetesDeployModeType defines the type of KubernetesDeployMode
Name of the deployment. When unset, this defaults to an autogenerated name.
KubernetesHorizontalPodAutoscalerSpec
KubernetesHorizontalPodAutoscalerSpec defines Kubernetes Horizontal Pod Autoscaler settings of Envoy Proxy Deployment.
When HPA is enabled, it is recommended that the value in KubernetesDeploymentSpec.replicas be removed, otherwise
Envoy Gateway will revert back to this value every time reconciliation occurs.
See k8s.io.autoscaling.v2.HorizontalPodAutoScalerSpec.
metrics contains the specifications for which to use to calculate the desired replica count (the maximum replica count across all metrics will be used). If left empty, it defaults to being based on CPU utilization with average on 80% usage.
behavior configures the scaling behavior of the target in both Up and Down directions (scaleUp and scaleDown fields respectively). If not set, the default HPAScalingRules for scale up and scale down are used. See k8s.io.autoscaling.v2.HorizontalPodAutoScalerBehavior.
Patch defines how to perform the patch operation to the HorizontalPodAutoscaler
name
string
false
Name of the horizontalPodAutoScaler. When unset, this defaults to an autogenerated name.
KubernetesPatchSpec
KubernetesPatchSpec defines how to perform the patch operation.
Note that value can be an in-line YAML document, as can be seen in e.g. (the example of patching the Envoy proxy Deployment)[https://gateway.envoyproxy.io/docs/tasks/operations/customize-envoyproxy/#patching-deployment-for-envoyproxy].
Note also that, currently, strings containing literal JSON are rejected.
Warning: this patch is merged directly onto the fully-computed Kubernetes resource with no
allowlist on which fields may be set. Whoever can author the EnvoyProxy resource that carries
this patch can therefore set arbitrary fields — including hostPath volumes, hostNetwork/hostPID,
privileged containers, or an arbitrary image/command — on a resource that Envoy Gateway’s own,
more privileged, ServiceAccount applies. Because EnvoyProxy is commonly namespace-scoped and
tenant-authored, treat this field as untrusted input in multi-tenant clusters: restrict who may
set it via RBAC, or disable EnvoyGateway’s EnvoyProxyPatch runtime flag.
MinAvailable specifies the minimum amount of pods (can be expressed as integers or as a percentage) that must be available at all times during voluntary disruptions, such as node drains or updates. This setting ensures that your envoy proxy maintains a certain level of availability and resilience during maintenance operations. Cannot be combined with maxUnavailable.
MaxUnavailable specifies the maximum amount of pods (can be expressed as integers or as a percentage) that can be unavailable at all times during voluntary disruptions, such as node drains or updates. This setting ensures that your envoy proxy maintains a certain level of availability and resilience during maintenance operations. Cannot be combined with minAvailable.
SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field.
TopologySpreadConstraints describes how a group of pods ought to spread across topology domains. Scheduler will schedule pods in a way which abides by the constraints. All topologySpreadConstraints are ANDed.
Type determines how the Service is exposed. Defaults to LoadBalancer. Valid options are ClusterIP, LoadBalancer and NodePort. “LoadBalancer” means a service will be exposed via an external load balancer (if the cloud provider supports it). “ClusterIP” means a service will only be accessible inside the cluster, via the cluster IP. “NodePort” means a service will be exposed on a static Port on all Nodes of the cluster.
loadBalancerClass
string
false
LoadBalancerClass, when specified, allows for choosing the LoadBalancer provider implementation if more than one are available or is otherwise expected to be specified
allocateLoadBalancerNodePorts
boolean
false
AllocateLoadBalancerNodePorts defines if NodePorts will be automatically allocated for services with type LoadBalancer. Default is “true”. It may be set to “false” if the cluster load-balancer does not rely on NodePorts. If the caller requests specific NodePorts (by specifying a value), those requests will be respected, regardless of this field. This field may only be set for services with type LoadBalancer and will be cleared if the type is changed to any other type.
loadBalancerSourceRanges
string array
false
LoadBalancerSourceRanges defines a list of allowed IP addresses which will be configured as firewall rules on the platform providers load balancer. This is not guaranteed to be working as it happens outside of kubernetes and has to be supported and handled by the platform provider. This field may only be set for services with type LoadBalancer and will be cleared if the type is changed to any other type.
loadBalancerIP
string
false
LoadBalancerIP defines the IP Address of the underlying load balancer service. This field may be ignored if the load balancer provider does not support this feature. This field has been deprecated in Kubernetes, but it is still used for setting the IP Address in some cloud providers such as GCP.
ExternalTrafficPolicy determines the externalTrafficPolicy for the Envoy Service. Valid options are Local and Cluster. Default is “Local”. “Local” means traffic will only go to pods on the node receiving the traffic. “Cluster” means connections are loadbalanced to all pods in the cluster.
Type indicates what watch mode to use. KubernetesWatchModeTypeNamespaces and KubernetesWatchModeTypeNamespaceSelector are currently supported By default, when this field is unset or empty, Envoy Gateway will watch for input namespaced resources from all namespaces.
namespaces
string array
true
Namespaces holds the list of namespaces that Envoy Gateway will watch for namespaced scoped resources such as Gateway, HTTPRoute and Service. The namespace where Envoy Gateway runs is always included so Envoy Gateway can reconcile its own managed infrastructure resources. Note that Envoy Gateway will continue to reconcile relevant cluster scoped resources such as GatewayClass that it is linked to. Precisely one of Namespaces and NamespaceSelector must be set.
NamespaceSelector holds the label selector used to dynamically select namespaces. Envoy Gateway will watch for namespaces matching the specified label selector. The namespace where Envoy Gateway runs is always included so Envoy Gateway can reconcile its own managed infrastructure resources. Precisely one of Namespaces and NamespaceSelector must be set.
KubernetesWatchModeType
Underlying type:string
KubernetesWatchModeType defines the type of KubernetesWatchMode
LeaseDuration defines the time non-leader contenders will wait before attempting to claim leadership. It’s based on the timestamp of the last acknowledged signal. The default setting is 15 seconds.
RenewDeadline represents the time frame within which the current leader will attempt to renew its leadership status before relinquishing its position. The default setting is 10 seconds.
Type decides the type of Load Balancer policy. Valid LoadBalancerType values are “ConsistentHash”, “LeastRequest”, “Random”, “RoundRobin”, “BackendUtilization”, “DynamicModule”.
EndpointOverride defines the configuration for endpoint override. When specified, the load balancer will attempt to route requests to endpoints based on the override information extracted from request headers or metadata. If the override endpoints are not available, the configured load balancer policy will be used as fallback.
SlowStart defines the configuration related to the slow start load balancer policy. If set, during slow start window, traffic sent to the newly added hosts will gradually increase. Supported for RoundRobin, LeastRequest, and BackendUtilization load balancers.
ValueRef is a reference to a local ConfigMap that contains the JSON Web Key Sets (JWKS). The value of key jwks in the ConfigMap will be used. If the key is not found, the first value in the ConfigMap will be used.
LocalJWKSType
Underlying type:string
LocalJWKSType defines the types of values for Local JWKS.
Rules are a list of RateLimit selectors and limits. If a request matches multiple rules, the strictest limit is applied. For example, if a request matches two rules, one with 10rps and one with 20rps, the final limit will be based on the rule with 10rps.
LocalWasmModuleSource
LocalWasmModuleSource defines a Wasm module loaded from the local filesystem.
ValueRef has the source code specified as a local object reference. Only a reference to ConfigMap is supported. The value of key lua in the ConfigMap will be used. If the key is not found, the first value in the ConfigMap will be used.
FilterContext is the filter context configuration for the Lua script. This must be a JSON object (key/value pairs). The values are made available to the Lua script via request_handle:filterContext(). This allows a shared script to be parameterized differently per EnvoyExtensionPolicy/route.
LuaValidationStrict is the default level and checks for issues during script execution. Recommended if your scripts only use the standard Envoy Lua stream handle API and no external libraries. For supported APIs, see: https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/lua_filter#stream-handle-api INFO: This validation mode executes Lua scripts from EnvoyExtensionPolicy (EEP) resources in the gateway controller. Since the Gateway controller watches EEPs across all namespaces (or namespaces matching the configured selector), unprivileged users can create EEPs in their namespaces and cause arbitrary Lua code to execute in the Gateway controller process. Security measures are in place to prevent unsafe Lua code from accessing critical system resources on the controller and fail validation, preventing the unsafe code from flowing to the data plane proxy.
InsecureSyntax
LuaValidationInsecureSyntax checks for Lua syntax errors only. Useful if your scripts use external libraries other than the standard Envoy Lua stream handle API. WARNING: This mode does NOT offer any runtime validations, so no security measures are applied to validate Lua code safety. Not recommended unless you completely trust all EnvoyExtensionPolicy resources.
Disabled
LuaValidationDisabled disables all Lua script validations. WARNING: This mode does NOT offer any runtime or syntax validations, so no security measures are applied to validate Lua code safety. Not recommended unless you completely trust all EnvoyExtensionPolicy resources.
LuaValidationConfig
LuaValidationConfig configures how Lua scripts from EnvoyExtensionPolicy resources are validated
in the gateway controller.
StrictValidation configures the security sandbox that the Strict validation mode executes Lua scripts in, defining the filesystem paths and environment variables the scripts are permitted to access during validation. It has no effect for the InsecureSyntax or Disabled modes, which do not execute the security sandbox.
LuaValueType
Underlying type:string
LuaValueType defines the types of values for Lua supported by Envoy Gateway.
LuaValueTypeValueRef defines the “ValueRef” Lua type.
MergeBackendsConfig
MergeBackendsConfig configures backend cluster deduplication (MergeBackends). Its mere
presence on EnvoyProxySpec enables it; a backendRef is only merged into a shared cluster when
safe to do so, otherwise it falls back to a dedicated per-route cluster.
Selector restricts cluster deduplication to backends whose target Service, ServiceImport, or Backend resource matches this label selector. When unset, every otherwise-eligible backend is merged. Use this to opt individual backends into deduplication gradually instead of enabling it for every backend at once.
The Kubernetes secret which contains the client ID to be used in the Authentication Request. Exactly one of clientID or clientIDRef must be set. This is an Opaque secret. The client ID should be stored in the key “client-id”. Only one of clientID or clientIDRef must be set.
The Kubernetes secret which contains the OIDC client secret to be used in the Authentication Request. This is an Opaque secret. The client secret should be stored in the key “client-secret”.
CookieNames configures the names of the cookies that Envoy sets for the Authentication Request. By default, every cookie is named “-”, where the suffix is derived from the identity of this SecurityPolicy. Set “suffix” to pin that suffix for all cookies at once, or set a per-cookie field to name a single cookie outright.
CookieConfigs allows setting the SameSite attribute for OIDC cookies. By default, its unset.
cookieDomain
string
false
The optional domain to set the access and ID token cookies on. If not set, the cookies will default to the host of the request, not including the subdomains. If set, the cookies will be set on the specified domain and all subdomains. This means that requests to any subdomain will not require reauthentication after users log in to the parent domain.
scopes
string array
false
The OIDC scopes to be used in the Authentication Request. The “openid” scope is always added to the list of scopes if not already specified.
The redirect URL to be used in the OIDC Authentication Request. If not specified, uses the default redirect URI “%REQ(x-forwarded-proto)%://%REQ(:authority)%/oauth2/callback”
Any request that matches any of the provided matchers (with either tokens that are expired or missing tokens) will not be redirected to the OIDC Provider. This behavior can be useful for AJAX or machine requests.
logoutPath
string
true
The path to log a user out, clearing their credential cookies. If not specified, uses a default logout path “/logout”
PostLogoutRedirect configures the post_logout_redirect_uri parameter that EG sends to the OIDC Provider’s end session endpoint when a user accesses the logout path. This only applies when the OIDC Provider’s end session endpoint is configured or discovered, i.e. when RP-Initiated Logout is in use. It is ignored otherwise. If not specified, Envoy sends the root of the request’s host, “:///”. Note that many OIDC Providers require the post logout redirect URI to be pre-registered for the client and reject the logout request otherwise. If the default value is not registered, set an explicit uri here, or set disabled to true to omit the parameter altogether.
forwardAccessToken
boolean
false
ForwardAccessToken indicates whether the Envoy should forward the access token via the Authorization header Bearer scheme to the upstream. If not specified, defaults to false.
ForwardIDToken configures forwarding of the OIDC ID token to the upstream. If the configured header is “Authorization”, EG forwards the ID token using the “Bearer " prefix. For any other header, EG forwards the raw token value. If not specified, the ID token will not be forwarded. Note: when passThroughAuthHeader is enabled, this header must not be the same as a header a JWT provider extracts from (the “Authorization” header by default). The forwarded ID token header is owned by Envoy, and Envoy rejects an OAuth2 configuration whose pass-through matcher keys on it.
DefaultTokenTTL is the default lifetime of the id token and access token. Please note that Envoy will always use the expiry time from the response of the authorization server if it is provided. This field is only used when the expiry time is not provided by the authorization. If not specified, defaults to 0. In this case, the “expires_in” field in the authorization response must be set by the authorization server, or the OAuth flow will fail.
refreshToken
boolean
false
true
RefreshToken indicates whether the Envoy should automatically refresh the id token and access token when they expire. When set to true, the Envoy will use the refresh token to get a new id token and access token when they expire. If not specified, defaults to true.
DefaultRefreshTokenTTL is the default lifetime of the refresh token. This field is only used when the exp (expiration time) claim is omitted in the refresh token or the refresh token is not JWT. If not specified, defaults to 604800s (one week). Note: this field is only applicable when the “refreshToken” field is set to true.
CSRFTokenTTL defines how long the CSRF token generated during the OAuth2 authorization flow remains valid. This duration determines the lifetime of the CSRF cookie, which is validated against the CSRF token in the “state” parameter when the provider redirects back to the callback endpoint. If omitted, Envoy Gateway defaults the token expiration to 10 minutes.
CodeVerifierTTL defines how long the PKCE code verifier generated during the OAuth2 authorization flow remains valid. This duration determines the lifetime of the code verifier cookie, which is exchanged for the access token when the provider redirects back to the callback endpoint. Both this cookie and the CSRF cookie are only consumed on the callback endpoint, so an authorization flow that is started but never completed leaves them behind until they expire. Lowering this value along with csrfTokenTTL bounds how many such cookies a browser can accumulate. It must stay long enough for a user to complete the login, including any multi-factor prompt: once it elapses the browser drops the cookie and the callback fails. If omitted, Envoy Gateway defaults the code verifier expiration to 10 minutes.
disableTokenEncryption
boolean
false
Disable token encryption. When set to true, both the access token and the ID token will be stored in plain text. This option should only be used in secure environments where token encryption is not required. Default is false (tokens are encrypted).
passThroughAuthHeader
boolean
false
Skips OIDC authentication when the request contains a header that will be extracted by the JWT filter. Unless explicitly stated otherwise in the extractFrom field, this will be the “Authorization: Bearer …” header. The passThroughAuthHeader option is typically used for non-browser clients that may not be able to handle OIDC redirects and wish to directly supply a token instead. If not specified, defaults to false.
OIDCCookieConfig
OIDCCookieConfig defines the cookie configuration for OAuth2 cookies.
OIDCCookieNames defines the names of the cookies that Envoy sets for the OIDC flow.
Envoy Gateway names every cookie “-”. By default the suffix is
derived from the identity of the SecurityPolicy, which keeps the cookies of
different policies from overwriting each other. Suffix replaces that generated
suffix for all cookies at once, while the per-cookie fields replace the entire
name of a single cookie and take precedence over Suffix.
Each cookie holds a different value, so the resulting names must be distinct,
otherwise the cookies would overwrite each other and break the OIDC flow.
Suffix replaces the generated suffix in the default name of every OAuth2 cookie, for example “AccessToken-” and “IdToken-”. The generated suffix is derived from the identity of the SecurityPolicy, so it changes when the policy is deleted and recreated, which logs users out. Set this field to keep the cookie names stable across the lifetime of the policy, or to share a session between policies that authenticate the same users against the same provider. Policies sharing a suffix must also agree on the OIDC provider, the client, and the cookieDomain. If not specified, the generated suffix is used.
accessToken
string
false
The name of the cookie used to store the AccessToken in the Authentication Request. If not specified, defaults to “AccessToken-”, see the “suffix” field.
oauthExpires
string
false
The name of the cookie used to store the OAuth expires value. If not specified, defaults to “OauthExpires-”, see the “suffix” field.
oauthHmac
string
false
The name of the cookie used to store the OAuth HMAC value. If not specified, defaults to “OauthHMAC-”, see the “suffix” field.
idToken
string
false
The name of the cookie used to store the IdToken in the Authentication Request. If not specified, defaults to “IdToken-”, see the “suffix” field.
refreshToken
string
false
The name of the cookie used to store the RefreshToken. If not specified, defaults to “RefreshToken-”, see the “suffix” field.
oauthNonce
string
false
The name of the cookie used to store the OAuth nonce value. If not specified, defaults to “OauthNonce-”, see the “suffix” field.
codeVerifier
string
false
The name of the cookie used to store the PKCE code verifier. If not specified, defaults to “CodeVerifier-”, see the “suffix” field.
OIDCDenyRedirect
OIDCDenyRedirect defines headers to match against the request to deny redirect to the OIDC Provider.
URI is sent as the post_logout_redirect_uri parameter to the OIDC Provider’s end session endpoint. The provider redirects the user to this URI after the logout completes, so it usually must be pre-registered for the client with the provider. The URI may contain the Envoy “%REQ(header)%" command operator to build the URI from the request, for example "%REQ(x-forwarded-proto)%://%REQ(:authority)%/loggedout”. Envoy Gateway accepts only that operator here, since it is the only one meaningful in a URI derived from the request, and rejects any other so that a typo surfaces on this policy instead of being rejected by Envoy as an invalid configuration. A literal percent is written as “%%”. The scheme must be http, https, or a “%REQ(header)%” command operator. The URI is percent-encoded automatically when the logout URL is built, so do not pre-encode it.
disabled
boolean
false
Disabled omits the post_logout_redirect_uri parameter from the logout request entirely. Use this when the OIDC Provider rejects unregistered post logout redirect URIs and you do not need the user redirected back after the logout completes. In that case the user is left on a page controlled by the provider. Setting this to false is equivalent to leaving disabled unset.
OIDCProvider
OIDCProvider defines the OIDC Provider configuration.
BackendRefs is used to specify the address of the OIDC Provider.
If the BackendRefs is not specified, The host and port of the OIDC Provider’s token endpoint
will be used as the address of the OIDC Provider.
TLS configuration can be specified in a BackendTLSConfig resource and target the BackendRefs.
Other settings for the connection to the OIDC Provider can be specified in the BackendSettings resource.
BackendRef references a Kubernetes object that represents the backend server to which the authorization request will be sent. Deprecated: Use BackendRefs instead. This field will be removed in v1.11.
BackendSettings holds configuration for managing the connection to the backend.
issuer
string
true
The OIDC Provider’s issuer identifier. Issuer MUST be a URI RFC 3986 [RFC3986] with a scheme component that MUST be https, a host component, and optionally, port and path components and no query or fragment components.
The OIDC Provider’s end session endpoint. If the end session endpoint is provided, EG will use it to log out the user from the OIDC Provider when the user accesses the logout path. EG will also try to discover the end session endpoint from the provider’s Well-Known Configuration Endpoint when authorizationEndpoint or tokenEndpoint is not provided.
OIDCTokenForwarding
OIDCTokenForwarding defines how an OIDC token is forwarded upstream.
Header is the upstream request header that will carry the ID token. It must be a valid HTTP header name. Pseudo-headers (names starting with “:”) and the “Host” header are not allowed.
OTelSampler
OTelSampler configures the OpenTelemetry sampler.
Type maps to OTEL_TRACES_SAMPLER.
BackendRef references a Kubernetes object that represents the backend server to which the authorization request will be sent. Deprecated: Use BackendRefs instead. This field will be removed in v1.11.
BackendSettings holds configuration for managing the connection to the backend.
host
string
false
Host define the extension service hostname. Deprecated: Use BackendRefs instead. This field will be removed in v1.11.
port
integer
false
4317
Port defines the port the extension service is exposed on. Deprecated: Use BackendRefs instead. This field will be removed in v1.11.
resources
object (keys:string, values:string)
false
Resources is a set of labels that describe the source of a log entry, including envoy node info. It’s recommended to follow semantic conventions. Deprecated: Use ResourceAttributes instead.
resourceAttributes
object (keys:string, values:string)
false
ResourceAttributes is a set of labels that describe the source of a log entry, including envoy node info. It’s recommended to follow semantic conventions.
Methods are the HTTP methods of the request. If multiple methods are specified, all specified methods are allowed or denied, based on the action of the rule.
Path is the HTTP path of the request. Support Exact, PathPrefix and RegularExpression match types.
Origin
Underlying type:string
Origin is defined by the scheme (protocol), hostname (domain), and port of
the URL used to access it. The hostname can be “precise” which is just the
domain name or “wildcard” which is a domain name prefixed with a single
wildcard label such as “*.example.com”.
In addition to that a single wildcard (with or without scheme) can be
configured to match any origin.
ReportingPeriod is how often Envoy requests load reports from the server. Must be greater than 0. Defaults to 10s.
port
integer
false
Port overrides the port used for the OutOfBand reporting connection, e.g. to reach a separate reporting sidecar. Defaults to the endpoint’s port.
authority
string
false
Authority overrides the :authority header on the OutOfBand gRPC stream. If unset, Envoy uses the endpoint hostname, then the dialed address, then the cluster name.
Interval defines the time between passive health checks.
consecutiveLocalOriginFailures
integer
false
5
ConsecutiveLocalOriginFailures sets the number of consecutive local origin failures triggering ejection. Parameter takes effect only when split_external_local_origin_errors is set to true.
consecutiveGatewayErrors
integer
false
ConsecutiveGatewayErrors sets the number of consecutive gateway errors triggering ejection.
consecutive5XxErrors
integer
false
5
Consecutive5xxErrors sets the number of consecutive 5xx errors triggering ejection.
BaseEjectionTime defines the base duration for which a host will be ejected on consecutive failures.
maxEjectionPercent
integer
false
10
MaxEjectionPercent sets the maximum percentage of hosts in a cluster that can be ejected.
failurePercentageThreshold
integer
false
FailurePercentageThreshold sets the failure percentage threshold for outlier detection. If the failure percentage of a given host is greater than or equal to this value, it will be ejected. Defaults to 85.
alwaysEjectOneEndpoint
boolean
false
false
AlwaysEjectOneEndpoint defines whether at least one host should be ejected, regardless of MaxEjectionPercent.
PathEscapedSlashAction
Underlying type:string
PathEscapedSlashAction determines the action for requests that contain %2F, %2f, %5C, or %5c
sequences in the URI path.
KeepUnchangedAction keeps escaped slashes as they arrive without changes
RejectRequest
RejectRequestAction rejects client requests containing escaped slashes with a 400 status. gRPC requests will be rejected with the INTERNAL (13) error code. The “httpN.downstream_rq_failed_path_normalization” counter is incremented for each rejected request.
UnescapeAndRedirect
UnescapeAndRedirect unescapes %2F and %5C sequences and redirects to the new path if these sequences were present. Redirect occurs after path normalization and merge slashes transformations if they were configured. gRPC requests will be rejected with the INTERNAL (13) error code. This option minimizes possibility of path confusion exploits by forcing request with unescaped slashes to traverse all parties: downstream client, intermediate proxies, Envoy and upstream server. The “httpN.downstream_rq_redirected_with_normalized_path” counter is incremented for each redirected request.
UnescapeAndForward
UnescapeAndForward unescapes %2F and %5C sequences and forwards the request. Note: this option should not be enabled if intermediaries perform path based access control as it may lead to path confusion vulnerabilities.
PathMatch
PathMatch defines the matching criteria for the HTTP path of a request.
EscapedSlashesAction determines how %2f, %2F, %5c, or %5C sequences in the path URI should be handled. The default is UnescapeAndRedirect.
disableMergeSlashes
boolean
false
DisableMergeSlashes allows disabling the default configuration of merging adjacent slashes in the path. Note that slash merging is not part of the HTTP spec and is provided for convenience.
PerEndpointCircuitBreakers
PerEndpointCircuitBreakers defines Circuit Breakers that will apply per-endpoint for an upstream cluster
MaxConnections configures the maximum number of connections that Envoy will establish per-endpoint to the referenced backend defined within a xRoute rule.
TargetRef is the name of the resource this policy is being attached to. This policy and the TargetRef MUST be in the same namespace for this Policy to have effect Deprecated: use targetRefs/targetSelectors instead. This field will be removed in v1.11.
targetRefs
LocalPolicyTargetReferenceWithSectionName array
true
TargetRefs are the names of the Gateway resources this policy is being attached to.
PerEndpointPercent configures how many additional connections to maintain per upstream endpoint, useful for high-QPS or latency sensitive services. Expressed as a percentage of the connections required by active streams (e.g. 100 = preconnect disabled, 105 = 1.05x connections per-endpoint, 200 = 2.00×). Allowed value range is between 100-300. When both PerEndpointPercent and PredictivePercent are set, Envoy ensures both are satisfied (max of the two).
predictivePercent
integer
false
PredictivePercent configures how many additional connections to maintain across the cluster by anticipating which upstream endpoint the load balancer will select next, useful for low-QPS services. Relies on deterministic loadbalancing and is only supported with Random or RoundRobin. Expressed as a percentage of the connections required by active streams (e.g. 100 = 1.0 (no preconnect), 105 = 1.05× connections across the cluster, 200 = 2.00×). Minimum allowed value is 100. When both PerEndpointPercent and PredictivePercent are set Envoy ensures both are satisfied per host (max of the two).
PreferLocalZone
PreferLocalZone configures zone-aware routing to prefer sending traffic to the local locality zone.
ForceLocalZone defines override configuration for forcing all traffic to stay within the local zone instead of the default behavior which maintains equal distribution among upstream endpoints while sending as much traffic as possible locally.
minEndpointsThreshold
integer
false
MinEndpointsThreshold is the minimum number of total upstream endpoints across all zones required to enable zone-aware routing.
percentageEnabled
integer
false
Configures percentage of requests that will be considered for zone aware routing if zone aware routing is configured. If not specified, Envoy defaults to 100%.
failTrafficOnPanic
boolean
false
FailTrafficOnPanic rejects traffic instead of routing to all endpoints when the cluster is in panic mode. Panic mode is entered when the share of healthy endpoints drops below HealthCheck.PanicThreshold, and by default Envoy then load balances across every endpoint, healthy or not. Setting this to true makes Envoy fail the requests instead, applying backpressure to clients and giving the backend room to recover. Defaults to false.
Principal
Principal specifies the client identity of a request.
A client identity can be a client IP, a JWT claim, username from the Authorization header,
or any other identity that can be extracted from a custom header.
If there are multiple principal types, all principals must match for the rule to match.
ClientCIDRs are the IP CIDR ranges of the client. Valid examples are “192.168.1.0/24” or “2001:db8::/64” If multiple CIDR ranges are specified, one of the CIDR ranges must match the client IP for the rule to match. The client IP is inferred from the X-Forwarded-For header, a custom header, or the proxy protocol. You can use the ClientIPDetection or the ProxyProtocol field in the ClientTrafficPolicy to configure how the client IP is detected. For TCPRoute and UDPRoute targets (raw L4 traffic), HTTP headers such as X-Forwarded-For are not available. The client IP is obtained from the TCP connection’s peer address, or from the source address of the UDP datagram. If intermediaries (load balancers, NAT) terminate or proxy the traffic, the original client IP will only be available if the intermediary preserves the source address (for example by enabling the PROXY protocol or avoiding SNAT). Note that the PROXY protocol is not available on the UDP path, so a UDPRoute target relies entirely on the datagram source address being preserved. Ensure your L4 proxy is configured to preserve the source IP to enable correct client-IP matching for TCPRoute and UDPRoute targets.
JWT authorize the request based on the JWT claims and scopes. Note: in order to use JWT claims for authorization, you must configure the JWT authentication in the same SecurityPolicy.
Headers authorize the request based on user identity extracted from custom headers. If multiple headers are specified, all headers must match for the rule to match.
ClientIPGeoLocations authorizes the request based on geolocation metadata derived from the client IP. This field is supported for HTTPRoute and GRPCRoute authorization. It is not supported for TCPRoute or UDPRoute targets. If multiple entries are specified, one of the ClientIPGeoLocation entries must match for the rule to match. The client IP is inferred from the X-Forwarded-For header, a custom header, or the direct downstream connection source address (the TCP peer of the connection terminated by Envoy). You can use the ClientIPDetection field in the ClientTrafficPolicy to configure the client IP detection.
ProcessingModeOptions
ProcessingModeOptions defines if headers or body should be processed by the external service
and which attributes are sent to the processor
ValueRef references a ConfigMap in the same namespace that holds the descriptor set. The descriptor set is read from the proto-descriptor key, either in binaryData or in data, where it can be base64-encoded. If the ConfigMap has no data and only one binaryData entry, that entry is used. The descriptor set must include all the imported files. It can be generated with protoc --include_imports --descriptor_set_out=....
ProtocolUpgradeConfig
ProtocolUpgradeConfig specifies the configuration for protocol upgrades.
Type defines the type of accesslog format. When unset, both text and json can be specified.
text
string
false
Text defines the text accesslog format, following Envoy accesslog formatting, It’s required when the format type is “Text”. Envoy command operators may be used in the format. The format string documentation provides more information.
json
object (keys:string, values:string)
false
JSON is additional attributes that describe the specific event occurrence. Structured format for the envoy access logs. Envoy command operators can be used as values for fields within the Struct. It’s required when the format type is “JSON”.
Format defines the format of accesslog. This will be ignored if sink type is ALS.
matches
string array
true
Matches defines the match conditions for accesslog in CEL expression. An accesslog will be emitted only when one or more match conditions are evaluated to true. Invalid CEL expressions will be ignored.
Type defines the component emitting the accesslog, such as Listener and Route. If type not defined, the setting would apply to: (1) All Routes. (2) Listeners if and only if Envoy does not find a matching route for a request. If type is defined, the accesslog settings would apply to the relevant component (as-is).
ProxyAccessLogSinkTypeFile defines the file accesslog sink.
OpenTelemetry
ProxyAccessLogSinkTypeOpenTelemetry defines the OpenTelemetry accesslog sink. When the provider is Kubernetes, EnvoyGateway always sends k8s.namespace.name and k8s.pod.name as additional attributes.
JSONPatches is an array of JSONPatches to be applied to the default bootstrap. Patches are applied in the order in which they are defined.
ProxyHealthCheckLog
ProxyHealthCheckLog configures Envoy health check event logging.
Health check events (state transitions, failures, successes) are emitted
to each configured sink.
Matches defines which health check probe outcomes produce a log entry. When omitted or empty, all events are logged. Each value must be unique. Multiple values are ORed. If any failure type is specified then a success type must also be specified, and vice versa.
ProxyHealthCheckLogEventType
Underlying type:string
ProxyHealthCheckLogEventType specifies which health check probe outcomes produce a log entry.
ProxyHealthCheckLogEventTypeFailure logs every failed probe regardless of the host’s current health state (Envoy’s always_log_health_check_failures=true).
FailureSeriesStart
ProxyHealthCheckLogEventTypeFailureSeriesStart logs only the first failed probe of a consecutive failure run — the probe that starts a potential healthy→unhealthy transition, regardless of whether unhealthyThreshold is ultimately reached (Envoy’s always_log_health_check_failures=false).
Success
ProxyHealthCheckLogEventTypeSuccess logs every successful probe regardless of the host’s current health state (Envoy’s always_log_health_check_success=true).
HealthyTransition
ProxyHealthCheckLogEventTypeHealthyTransition logs the first successful probe of a consecutive success run AND when the host reaches the healthy threshold and transitions back to healthy (Envoy’s always_log_health_check_success=false).
ProxyHealthCheckLogSink
ProxyHealthCheckLogSink defines a destination for health check event logs.
Level is a map of logging level per component, where the component is the key and the log level is the value. If unspecified, defaults to “default: warn”.
ProxyMetricSink
ProxyMetricSink defines the sink of metrics.
Default metrics sink is OpenTelemetry.
Matches defines configuration for selecting specific metrics instead of generating all metrics stats that are enabled by default. This helps reduce CPU and memory overhead in Envoy, but eliminating some stats may after critical functionality. Here are the stats that we strongly recommend not disabling: cluster_manager.warming_clusters, cluster.<cluster_name>.membership_total,cluster.<cluster_name>.membership_healthy, cluster.<cluster_name>.membership_degraded,reference https://github.com/envoyproxy/envoy/issues/9856, https://github.com/envoyproxy/envoy/issues/14610
enableVirtualHostStats
boolean
false
EnableVirtualHostStats enables envoy stat metrics for virtual hosts.
enablePerEndpointStats
boolean
false
EnablePerEndpointStats enables per endpoint envoy stats metrics. Please use with caution.
enableRequestResponseSizesStats
boolean
false
EnableRequestResponseSizesStats enables publishing of histograms tracking header and body sizes of requests and responses.
EnableGRPCStats enables the gRPC stats filter on listeners. This is enabled by default for GRPCRoute and opt-in for HTTPRoute. In general, gRPC traffic should be handled via GRPCRoute, but there are cases where users want to route gRPC using HTTPRoute for its richer matching capabilities. Therefore, we enable this behavior only when it is explicitly opted in.
clusterStatName
string
false
ClusterStatName defines the value of cluster alt_stat_name, determining how cluster stats are named. For more details, see envoy docs: https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/cluster/v3/cluster.proto.html The supported operators for this pattern are: %ROUTE_NAME%: name of Gateway API xRoute resource %ROUTE_NAMESPACE%: namespace of Gateway API xRoute resource %ROUTE_KIND%: kind of Gateway API xRoute resource %ROUTE_RULE_NAME%: name of the Gateway API xRoute section %ROUTE_RULE_NUMBER%: name of the Gateway API xRoute section %BACKEND_REFS%: names of all backends referenced in <NAMESPACE>/<NAME>|<NAMESPACE>/<NAME>|... format Only xDS Clusters created for HTTPRoute and GRPCRoute are currently supported. A cluster shared by several routes through MergeBackends has no single route, so this pattern isn’t applied to it. Its stats are named <NAMESPACE>/<NAME> after the backend instead, the value the %BACKEND_REFS% operator expands to for a rule with one backendRef. Default: %ROUTE_KIND%/%ROUTE_NAMESPACE%/%ROUTE_NAME%/rule/%ROUTE_RULE_NUMBER% Example: httproute/my-ns/my-route/rule/0
ProxyOpenTelemetrySink
ProxyOpenTelemetrySink defines the configuration for OpenTelemetry sink.
BackendRef references a Kubernetes object that represents the backend server to which the authorization request will be sent. Deprecated: Use BackendRefs instead. This field will be removed in v1.11.
BackendSettings holds configuration for managing the connection to the backend.
host
string
false
Host define the service hostname. Deprecated: Use BackendRefs instead. This field will be removed in v1.11.
port
integer
false
4317
Port defines the port the service is exposed on. Deprecated: Use BackendRefs instead. This field will be removed in v1.11.
reportCountersAsDeltas
boolean
false
ReportCountersAsDeltas configures the OpenTelemetry sink to report counters as delta temporality instead of cumulative.
reportHistogramsAsDeltas
boolean
false
ReportHistogramsAsDeltas configures the OpenTelemetry sink to report histograms as delta temporality instead of cumulative. Required for backends like Elastic that drop cumulative histograms.
prefix
string
false
Prefix configures the OpenTelemetry sink to prepend the given prefix to emitted stat names, the full stat name will be <prefix>.<stat_name>.
Configure the compression on Prometheus endpoint. Compression is useful in situations when bandwidth is scarce and large payloads can be effectively compressed at the expense of higher CPU load.
ProxyProtocol
ProxyProtocol defines the configuration related to the proxy protocol
when communicating with the backend.
Version of ProxyProtocol Valid ProxyProtocolVersion values are “V1” “V2”
ProxyProtocolSettings
ProxyProtocolSettings configures the Proxy Protocol settings. When configured,
the Proxy Protocol header will be interpreted and the Client Address
will be added into the X-Forwarded-For header.
If both EnableProxyProtocol and ProxyProtocol are set, ProxyProtocol takes precedence.
Optional allows requests without a Proxy Protocol header to be proxied. If set to true, the listener will accept requests without a Proxy Protocol header. If set to false, the listener will reject requests without a Proxy Protocol header. If not set, the default behavior is to reject requests without a Proxy Protocol header. Warning: Optional breaks conformance with the specification. Only enable if ALL traffic to the listener comes from a trusted source. For more information on security implications, see haproxy.org/download/2.1/doc/proxy-protocol.txt
ForwardProtoConfig infers the x-forwarded-proto header from the PROXY protocol destination port. Only takes effect when PROXY protocol is enabled. This is useful when a Layer 4 load balancer (such as AWS NLB) terminates TLS and forwards traffic to Envoy over PROXY protocol, so that Envoy can set the correct scheme for the forwarded request.
ProxyProtocolVersion
Underlying type:string
ProxyProtocolVersion defines the version of the Proxy Protocol to use.
ClientSamplingFraction represents the fraction of requests that should be selected for tracing when requested by the client. If unspecified, client-forced tracing is disabled by default and users must set this field to opt in.
CustomTags defines the custom tags to add to each span. If provider is kubernetes, pod name and namespace are added by default. Deprecated: Use Tags instead.
tags
object (keys:string, values:string)
false
Tags defines the custom tags to add to each span. Envoy command operators may be used in the value. The format string documentation provides more information. If provider is kubernetes, pod name and namespace are added by default. Same keys take precedence over CustomTags.
SpanName defines the name of the span which will be used for tracing. Envoy command operators may be used in the value. The format string documentation provides more information. If not set, the span name is provider specific. e.g. Datadog use ingress as the default client span name, and router <UPSTREAM_CLUSTER> egress as the server span name.
samplingRate
integer
false
SamplingRate controls the rate at which traffic will be selected for tracing if no prior sampling decision has been made. Defaults to 100, valid values [0-100]. 100 indicates 100% sampling. Only one of SamplingRate or SamplingFraction may be specified. If neither field is specified, all requests will be sampled.
Type specifies how to match against the value of the query parameter.
name
string
true
Name of the query parameter.
value
string
false
Value of the query parameter. Do not set this field when Type=“Distinct”, implying matching on any/all unique values within the query parameter.
invert
boolean
false
false
Invert specifies whether the value match result will be inverted. Do not set this field when Type=“Distinct”, implying matching on any/all unique values within the query parameter.
QueryParamMatchType
Underlying type:string
QueryParamMatchType specifies the semantics of how query parameter values should be compared.
Valid QueryParamMatchType values are “Exact”, “RegularExpression”, and “Distinct”.
QueryParamMatchExact matches the exact value of the Value field against the value of the specified query parameter.
RegularExpression
QueryParamMatchRegularExpression matches a regular expression against the value of the specified query parameter. The regex string must adhere to the syntax documented in https://github.com/google/re2/wiki/Syntax.
Distinct
QueryParamMatchDistinct matches any and all possible unique values encountered in the specified query parameter. Note that each unique value will receive its own rate limit bucket.
RateLimit
RateLimit defines the configuration associated with the Rate Limit Service
used for Global Rate Limiting.
Backend holds the configuration associated with the database backend used by the rate limit service to store state associated with global ratelimiting.
Timeout specifies the timeout period for the proxy to access the ratelimit server If not set, timeout is 20ms.
failClosed
boolean
true
FailClosed is a switch used to control the flow of traffic when the response from the ratelimit server cannot be obtained. If FailClosed is false, let the traffic pass, otherwise, don’t let the traffic pass and return 500. If not set, FailClosed is False.
ServiceSettings holds configuration for the Envoy cluster that connects the proxies to the rate limit service, such as circuit breakers, timeouts and health checks. The rate limit service is a gRPC (HTTP/2) service reached over mTLS, with no associated route, so NOT all of the ClusterSettings fields are supported here. Fields are supported on a best-effort basis: a field that only applies to routes or to other protocols (e.g. timeout.http.streamIdleTimeout) may have no effect. Envoy Gateway fails to start if any of these known-unsupported fields are set: - http1, http3 and proxyProtocol: the rate limit service only accepts gRPC over mTLS. - healthCheck.active of type HTTP: the rate limit service only serves its HTTP health endpoint in plaintext; use the GRPC or TCP type instead. - timeout.http.requestTimeout: use RateLimit.Timeout instead. - loadBalancer of type ConsistentHash: there is no route to compute the hash from.
Request specifies the number to reduce the rate limit counters on the request path. If this is not specified, the default behavior is to reduce the rate limit counters by 1. When Envoy receives a request that matches the rule, it tries to reduce the rate limit counters by the specified number. If the counter doesn’t have enough capacity, the request is rate limited.
Response specifies the number to reduce the rate limit counters after the response is sent back to the client or the request stream is closed. The cost is used to reduce the rate limit counters for the matching requests. Since the reduction happens after the request stream is complete, the rate limit won’t be enforced for the current request, but for the subsequent matching requests. This is optional and if not specified, the rate limit counters are not reduced on the response path.
refundOnResponse
boolean
false
RefundOnResponse gives the request cost back to the counters when the stream is closed instead of consuming another cost. This tracks the number of requests in flight for each descriptor, which can be used to limit concurrency. This is only supported for a Number request cost and HTTP Global Rate Limits.
RateLimitCostFrom
Underlying type:string
RateLimitCostFrom specifies the source of the rate limit cost.
Valid RateLimitCostType values are “Number” and “Metadata”.
From specifies where to get the rate limit cost. Currently, only “Number” and “Metadata” are supported.
number
integer
false
Number specifies the fixed usage number to reduce the rate limit counters. Using zero can be used to only check the rate limit counters without reducing them.
URL of the Redis Database. This can reference a single Redis host or a comma delimited list for Sentinel and Cluster deployments of Redis. Mutually exclusive with URLRef.
URLRef sources the Redis URL from a Kubernetes Secret key. Use this for GitOps flows where the Redis endpoint is provisioned by an external controller. The referenced Secret must exist in the namespace of the Envoy Gateway rate limit deployment. Mutually exclusive with URL.
ClientSelectors holds the list of select conditions to select specific clients using attributes from the traffic flow. All individual select conditions must hold True for this rule and its limit to be applied. If no client selectors are specified, the rule applies to all traffic of the targeted Route. If the policy targets a Gateway, the rule applies to each Route of the Gateway. Please note that each Route has its own rate limit counters. For example, if a Gateway has two Routes, and the policy has a rule with limit 10rps, each Route will have its own 10rps limit.
Limit holds the rate limit values. This limit is applied for traffic flows when the selectors compute to True, causing the request to be counted towards the limit. The limit is enforced and the request is ratelimited, i.e. a response with 429 HTTP status code is sent back to the client when the selected requests have reached the limit.
Cost specifies the cost of requests and responses for the rule. This is optional and if not specified, the default behavior is to reduce the rate limit counters by 1 on the request path and do not reduce the rate limit counters on the response path.
shared
boolean
false
Shared determines whether this rate limit rule applies across all the policy targets. If set to true, the rule is treated as a common bucket and is shared across all policy targets (xRoutes). Default: false.
shadowMode
boolean
false
ShadowMode indicates whether this rate-limit rule runs in shadow mode. When enabled, all rate-limiting operations are performed (cache lookups, counter updates, telemetry generation), but the outcome is never enforced. The request always succeeds, even if the configured limit is exceeded. Only supported for Global Rate Limits.
XRateLimitHeaders controls whether X-RateLimit response headers are emitted for this rate limit rule. When set, this overrides the global DisableRateLimitHeaders setting in ClientTrafficPolicy for this rule. If not set, the rule inherits the listener-level setting (default behavior).
RateLimitSelectCondition
RateLimitSelectCondition specifies the attributes within the traffic flow that can
be used to select a subset of clients to be ratelimited.
All the individual conditions must hold True for the overall condition to hold True.
And, at least one of headers or methods or path or sourceCIDR or queryParams condition must be specified.
Methods is a list of request methods to match. Multiple method values are ORed together, meaning, a request can match any one of the specified methods. If not specified, it matches all methods.
QueryParams is a list of query parameters to match. Multiple query parameter values are ANDed together, meaning, a request MUST match all the specified query parameters.
RateLimitSpec
RateLimitSpec defines the desired state of RateLimitSpec.
Type decides the scope for the RateLimits. Valid RateLimitType values are “Global” or “Local”. Deprecated: Use Global and/or Local fields directly instead. Both can be specified simultaneously for combined rate limiting.
SamplingRate controls the rate at which traffic will be selected for tracing if no prior sampling decision has been made. Defaults to 100, valid values [0-100]. 100 indicates 100% sampling.
GlobalRateLimitType allows the rate limits to be applied across all Envoy proxy instances.
Local
LocalRateLimitType allows the rate limits to be applied on a per Envoy proxy instance basis.
RateLimitUnit
Underlying type:string
RateLimitUnit specifies the intervals for setting rate limits.
Valid RateLimitUnit values are “Second”, “Minute”, “Hour”, “Day”, “Week”, “Month” and “Year”.
FromMetadata sources the limit value from per-request dynamic metadata. When the referenced metadata value is present, it overrides Requests/Unit for that request; otherwise Requests/Unit are used as the default. The referenced metadata value must be a struct containing an integer “requests_per_unit” property and a “unit” property with a value parseable to a RateLimitUnit. An upstream filter (e.g. ext_proc) is responsible for writing this struct into dynamic metadata. Only supported for Global Rate Limits.
RateLimitValueMetadata
RateLimitValueMetadata specifies the dynamic metadata to retrieve the limit value from.
SecretKeyRef references the Secret and key that hold the Redis URL. The Secret must be in the same namespace as the Envoy Gateway rate limit deployment. The reference is always required: optional must not be set to true, otherwise the rate limit pod could start with an unset REDIS_URL instead of waiting for the externally provisioned Secret.
RemoteDynamicModuleSource
RemoteDynamicModuleSource defines a dynamic module fetched from a remote HTTP source.
URL is the HTTP or HTTPS URL of the dynamic module shared library (.so file).
sha256
string
true
SHA256 checksum that Envoy will use to verify the downloaded module binary.
RemoteJWKS
RemoteJWKS defines how to fetch and cache JSON Web Key Sets (JWKS) from a remote HTTP/HTTPS endpoint.
BackendRefs is used to specify the address of the Remote JWKS.
If the BackendRefs is not specified, the URI field is used to determine the address of the Remote JWKS.
TLS configuration can be specified in a BackendTLSConfig resource and target the BackendRefs.
Other settings for the connection to the remote JWKS can be specified in the BackendSettings resource.
BackendRef references a Kubernetes object that represents the backend server to which the authorization request will be sent. Deprecated: Use BackendRefs instead. This field will be removed in v1.11.
BackendSettings holds configuration for managing the connection to the backend.
uri
string
true
URI is the HTTPS URI to fetch the JWKS. Envoy’s system trust bundle is used to validate the server certificate. If a custom trust bundle is needed, it can be specified in a BackendTLSConfig resource and target the BackendRefs.
FailedRefetchDuration is the duration Envoy waits before re-fetching the JWKS after a failed fetch. This does not control retries within a single fetch attempt (see BackendSettings.Retry), only the interval between fetch attempts after a failure. If not specified, Envoy’s default of 1 second is used.
Pattern matches a regular expression against the value of the HTTP Path.The regex string must adhere to the syntax documented in https://github.com/google/re2/wiki/Syntax.
substitution
string
true
Substitution is an expression that replaces the matched portion.The expression may include numbered capture groups that adhere to syntax documented in https://github.com/google/re2/wiki/Syntax.
Limit specifies the maximum size in bytes that Envoy may buffer for an incoming request body. If a request’s buffered body exceeds this limit, the request is rejected with HTTP 413 Content Too Large. In BufferAndLimit mode the entire body is always buffered, so this acts as a maximum request body size. In LimitOnly mode only what a filter later in the chain actually buffers counts against the limit, so a streamed request that nothing buffers can exceed it and still be forwarded upstream. Accepts values in resource.Quantity format (e.g., “10Mi”, “500Ki”).
Mode determines how Limit is enforced. Defaults to BufferAndLimit. Limit applies in both modes: it is always set as the request body buffer limit for the route. Mode only controls whether the gateway additionally buffers the whole request body itself, which is what makes Limit a guaranteed maximum request body size. BufferAndLimit makes the gateway receive each request from the client in full before it starts sending the request upstream to the backends. This can be helpful to shield your backend servers from slow clients, and Limit acts as a maximum request body size for the route. Buffering whole request bodies costs memory and adds latency, so this mode should only be used when necessary. It is also incompatible with streaming APIs and protocol upgrades such as gRPC streaming and WebSocket: HTTP upgrades are disabled on routes using this mode, and a request whose body is never completed is never forwarded upstream. Do not use this mode on routes that need those protocols. LimitOnly only raises how much of a request body the gateway is allowed to buffer, without buffering requests itself. Use this mode when something later in the request path (ext_proc, Lua, Wasm, …) buffers the request body and the default limit is too small. Unlike BufferAndLimit, this mode is compatible with streaming APIs and protocol upgrades, because the gateway does not wait for the whole request body before forwarding it upstream. In both modes, Limit applies to an individual request body and is separate from the connection buffer limits configured by ClientTrafficPolicy and BackendTrafficPolicy, which control per-connection read/write buffering and back pressure. There is no need to raise the connection buffer limits for Limit to take effect.
RequestBufferMode
Underlying type:string
RequestBufferMode determines how RequestBuffer.Limit is applied.
RequestBufferModeBufferAndLimit buffers the entire request body in the gateway before forwarding the request upstream, so Limit acts as a maximum request body size. It is incompatible with streaming APIs and protocol upgrades.
LimitOnly
RequestBufferModeLimitOnly only raises the request body buffer limit for the route, without enabling full request buffering.
RequestHeaderCustomTag
RequestHeaderCustomTag adds value from request header to each span.
Name defines the name of the request header which to extract the value from.
defaultValue
string
false
DefaultValue defines the default value to use if the request header is not set.
RequestIDAction
Underlying type:string
RequestIDAction configures Envoy’s behavior for handling the X-Request-ID header at the edge.
An “edge request” refers to a request from an external client to the Envoy entrypoint.
Preserve X-Request-ID if already present or generate if empty
Preserve
Preserve X-Request-ID if already present, do not generate when empty
Generate
Always generate X-Request-ID header, do not preserve X-Request-ID header if it exists. This is the default behavior.
Disable
Do not preserve or generate X-Request-ID header
RequestIDExtensionAction
Underlying type:string
RequestIDExtensionAction defines how the UUID request ID extension behaves
with respect to packing the trace reason into the UUID and using the
request ID for trace sampling decisions.
Tracing configures Envoy’s behavior for the UUID request ID extension, including whether the trace sampling decision is packed into the UUID and whether X-Request-ID is used for trace sampling decisions. When omitted, the default behavior is PackAndSample, which alters the UUID to contain the trace sampling decision and uses X-Request-ID for stable trace sampling.
Literal specifies a fixed hostname to rewrite the Host header to. Required when Type is “Literal”. Must be empty when Type is “Backend”. Note: gwapiv1.PreciseHostname already carries MinLength=1, MaxLength=253, and RFC 1123 pattern validation, which automatically flow into the generated CRD.
RequestMirrorHostnameModifierType
Underlying type:string
RequestMirrorHostnameModifierType defines the type of hostname rewrite for mirrored requests.
Source specifies which responses this rule applies to. Local overrides only Envoy-generated responses (e.g. auth failures). Backend overrides only upstream responses. All (default) overrides both.
ResponseOverrideHeaderMatch
ResponseOverrideHeaderMatch defines the configuration for matching a request or response header.
NumRetries is the number of retries to be attempted. Defaults to 2.
numAttemptsPerPriority
integer
false
NumAttemptsPerPriority defines the number of requests (initial attempt + retries) that should be sent to the same priority before switching to a different one. If not specified or set to 0, all requests are sent to the highest priority that is healthy.
RetryOn specifies the retry trigger condition. If not specified, the default is to retry on connect-failure,refused-stream,unavailable,cancelled,retriable-status-codes(503).
Percent specifies the limit on concurrent retries as a percentage [0, 100] of the sum of active requests and active pending requests.
minRetryConcurrency
integer
false
MinRetryConcurrency specifies the minimum retry concurrency allowed for the retry budget. For example, a budget of 20% with a minimum retry concurrency of 3 will allow 5 active retries while there are 25 active requests. If there are 2 active requests, there are still 3 active retries allowed because of the minimum retry concurrency. Defaults to 3.
HttpStatusCodes specifies the http status codes to be retried. The retriable-status-codes trigger must also be configured for these status codes to trigger a retry.
ServiceRoutingType is the RoutingType for Service Cluster IP routing.
Endpoint
EndpointRoutingType is the RoutingType for Endpoint routing.
RuntimeFlag
Underlying type:string
RuntimeFlag defines a runtime flag used to guard breaking changes or risky experimental features in new Envoy Gateway releases.
A runtime flag may be enabled or disabled by default and can be toggled through the EnvoyGateway resource.
XDSNameSchemeV2 indicates that the xds name scheme v2 is used. * The listener name will be generated using the protocol and port of the listener.
EndpointSliceIndex
EndpointSliceIndex indicates that field indexes are used to look up EndpointSlices by backend. It is enabled by default to reduce CPU usage for EndpointSlice lookups in large clusters. If the additional controller memory usage for the indexes becomes a concern, consider disabling this flag.
PerResourceSystemCASecret
PerResourceSystemCASecret restores the pre-1.x behavior of emitting one SDS secret per BackendTLSPolicy or Backend resource that uses WellKnownCACertificates: System, instead of sharing a single system_ca_certificates secret across all of them. Disabled by default (i.e. the shared secret is used). Enable this flag to opt out during upgrades — Envoy must warm the new system_ca_certificates secret before clusters can use it, which may cause a brief disruption to new connections on first enable.
EnvoyProxyPatch
EnvoyProxyPatch enables applying the Kubernetes resource patch fields configured on EnvoyProxy’s Kubernetes provider settings. It is enabled by default to preserve pre-existing behavior. Because EnvoyProxy is commonly namespace-scoped and tenant-authored, a patch may grant arbitrary access to resources applied by Envoy Gateway’s more privileged ServiceAccount; disable this flag in multi-tenant clusters where tenants can author their own EnvoyProxy resources.
ApplyClientTrafficPolicyHTTP1SettingsToClientsOnly restricts the ClientTrafficPolicy http1 fields (enableTrailers, preserveHeaderCase, http10) to client connections only. When enabled, these fields no longer affect backend HTTP/1 protocol settings. Use BackendTrafficPolicy.http1 to configure backend HTTP/1 protocol settings. Disabled by default to preserve existing behavior. Users are encouraged to migrate to BackendTrafficPolicy.http1 for backend settings and enable this flag to opt in to the new behavior. This flag will be enabled by default in a future release.
OIDCTokenCookieChunking
OIDCTokenCookieChunking splits an OIDC access, ID or refresh token too large for one browser cookie across several cookies, instead of the browser dropping it and the login looping back to the OIDC provider. It is enabled by default. Envoy Proxy older than v1.40 can’t read the split cookies, so a client that holds such a token in one cookie today, such as a non-browser client, is sent back to the OIDC provider when it reaches an older proxy. Disable this flag while proxies of an earlier Envoy Gateway release serve the same hostnames, for example during an upgrade.
RuntimeFlags
RuntimeFlags provide a mechanism to guard breaking changes or risky experimental features in new Envoy Gateway releases.
Each flag may be enabled or disabled by default and can be toggled through the EnvoyGateway resource.
The names of these flags will be included in the release notes alongside an explanation of the change.
Please note that these flags are temporary and will be removed in future releases once the related features are stable.
SchemeHeaderTransformPreserve preserves the :scheme from the original client request. This is the default behavior.
MatchBackend
SchemeHeaderTransformMatchBackend sets the :scheme to match the backend transport protocol. If the backend uses TLS, the scheme is “https”, otherwise “http”.
Status defines the current status of SecurityPolicy.
SecurityPolicySpec
SecurityPolicySpec defines the desired state of SecurityPolicy.
NOTE: SecurityPolicy can target Gateway, ListenerSet, HTTPRoute, GRPCRoute, TCPRoute,
TLSRoute, and UDPRoute.
When a SecurityPolicy targets a TCPRoute, TLSRoute, or UDPRoute, only client-IP CIDR based
authorization (Authorization rules that use Principal.ClientCIDRs) is applied. Other
authentication/authorization features such as JWT, API Key, Basic Auth,
OIDC, External Authorization, or GeoIP based authorization are not applicable
to TCPRoute, TLSRoute, or UDPRoute targets.
TargetRef is the name of the resource this policy is being attached to. This policy and the TargetRef MUST be in the same namespace for this Policy to have effect Deprecated: use targetRefs/targetSelectors instead. This field will be removed in v1.11.
targetRefs
LocalPolicyTargetReferenceWithSectionName array
true
TargetRefs are the names of the Gateway resources this policy is being attached to.
MergeType determines how this configuration is merged with existing SecurityPolicy configurations targeting a parent resource. When set, this configuration will be merged into the closest parent SecurityPolicy in the route’s attachment hierarchy (for example, one targeting a Gateway, Gateway listener, ListenerSet, or ListenerSet listener). Currently, this field can only be set when targeting xRoute resources. If unset, no merging occurs, and only the most specific configuration takes effect.
CSRF defines the configuration for Cross-Site Request Forgery (CSRF) protection. When enabled, the CSRF filter checks that the Origin header matches the destination or one of the additional allowed origins on mutating requests (POST, PUT, DELETE, PATCH).
Authorization defines the authorization configuration.
ServiceExternalTrafficPolicy
Underlying type:string
ServiceExternalTrafficPolicy describes how nodes distribute service traffic they
receive on one of the Service’s “externally-facing” addresses (NodePorts, ExternalIPs,
and LoadBalancer IPs.
ServiceExternalTrafficPolicyCluster routes traffic to all endpoints.
Local
ServiceExternalTrafficPolicyLocal preserves the source IP of the traffic by routing only to endpoints on the same node as the traffic was received on (dropping the traffic if there are no local endpoints).
ServiceType
Underlying type:string
ServiceType string describes ingress methods for a service
Resumption determines the proxy’s supported TLS session resumption option. By default, Envoy Gateway does not enable session resumption. Use sessionResumption to enable stateful and stateless session resumption. Users should consider security impacts of different resumption methods. Performance gains from resumption are diminished when Envoy proxy is deployed with more than one replica.
SessionResumption
SessionResumption defines supported tls session resumption methods and their associated configuration.
DrainTimeout defines the graceful drain timeout. This should be less than the pod’s terminationGracePeriodSeconds. If unspecified, defaults to 60 seconds.
DrainStrategy defines how Envoy drains HTTP connections during the graceful drain process. TCP and UDP proxy connections are not drained by either strategy. If unspecified, defaults to “Immediate”. Switching to or from “Gradual” changes the listener configuration, which makes the running Envoy proxies replace their listeners and drain the existing connections.
ShutdownManager
ShutdownManager defines the configuration for the shutdown manager.
Value is the IP CIDR that represents the range of Source IP Addresses of the client. These could also be the intermediate addresses through which the request has flown through and is part of the X-Forwarded-For header. For example, 192.168.0.1/32, 192.168.0.0/24, 001:db8::/64.
invert
boolean
false
false
Invert specifies whether the source range match result will be inverted. When true, the rule matches when the client IP is not in the specified range(s).
SourceMatchExact All IP Addresses within the specified Source IP CIDR are treated as a single client selector and share the same rate limit bucket.
Distinct
SourceMatchDistinct Each IP Address within the specified Source IP CIDR is treated as a distinct client selector and uses a separate rate limit bucket/counter.
AllowedPaths is the list of filesystem path prefixes that Lua scripts are permitted to access during validation (via io.open, io.input, io.output, io.lines, os.remove, os.rename). A path is allowed when it equals an entry or is contained within an entry’s subtree (e.g. “/tmp” allows “/tmp/file.txt”). Paths are normalized (separators collapsed, made absolute) before matching, and any “.” or “..” traversal segment is always rejected. When empty, all filesystem access is denied. Blank or whitespace-only entries are rejected, as they would otherwise match every path and disable the sandbox. The filesystem root (”/”) is likewise rejected, as it would allow access to the entire filesystem and defeat the sandbox. Note that a built-in set of sensitive paths is always denied, even if they are added to the allowed paths here: /etc, /proc, /sys, /certs, /var/run/secrets, and /run/secrets.
allowedEnvVars
string array
false
AllowedEnvVars is the list of environment variable names that Lua scripts are permitted to access during validation (via os.getenv, os.setenv). Matching is exact and case-sensitive. When empty, access to all environment variables is denied. Blank or whitespace-only entries are rejected.
StringMatch
StringMatch defines how to match any strings.
This is a general purpose match condition that can be used by other EG APIs
that need to match against a string.
Value specifies the string value that the match must have.
StringMatchType
Underlying type:string
StringMatchType specifies the semantics of how a string value should be compared.
Valid MatchType values are “Exact”, “Prefix”, “Suffix”, “RegularExpression”.
StringMatchExact :the input string must match exactly the match value.
Prefix
StringMatchPrefix :the input string must start with the match value.
Suffix
StringMatchSuffix :the input string must end with the match value.
RegularExpression
StringMatchRegularExpression :The input string must match the regular expression specified in the match value. The regex string must adhere to the syntax documented in https://github.com/google/re2/wiki/Syntax.
IdleTimeout for a TCP connection. Idle time is defined as a period in which there are no bytes sent or received on either the upstream or downstream connection. Default: 1 hour.
TLSHandshakeTimeout for a TCP connection. The maximum time to complete transport level connection negotiation (e.g. the TLS handshake) after a connection is accepted. If this expires before the transport reports connection establishment, the connection is summarily closed.
ConnectionInspectionTimeout is the maximum time to wait for initial inspection (TLS / SNI and protocol detection, or HTTP protocol parsing) of an incoming connection on the listener socket. If exceeded, the connection is dropped. Default: 15 seconds.
TCPKeepalive
TCPKeepalive define the TCP Keepalive configuration.
Max specifies the maximal TLS protocol version to allow The default is TLS 1.3 if this is not specified.
ciphers
string array
false
Ciphers specifies the set of cipher suites supported when negotiating TLS 1.0 - 1.2. This setting has no effect for TLS 1.3. For Envoy TLS cipher suite configuration semantics and default cipher lists, see the Envoy documentation: https://www.envoyproxy.io/docs/envoy/latest/api-v3/extensions/transport_sockets/tls/v3/common.proto#extensions-transport-sockets-tls-v3-tlsparameters Supported cipher suite names: - ECDHE-ECDSA-AES128-GCM-SHA256 - ECDHE-RSA-AES128-GCM-SHA256 - ECDHE-ECDSA-AES256-GCM-SHA384 - ECDHE-RSA-AES256-GCM-SHA384 - ECDHE-ECDSA-CHACHA20-POLY1305 - ECDHE-RSA-CHACHA20-POLY1305 - ECDHE-ECDSA-AES128-SHA - ECDHE-RSA-AES128-SHA - AES128-GCM-SHA256 - AES128-SHA - ECDHE-ECDSA-AES256-SHA - ECDHE-RSA-AES256-SHA - AES256-GCM-SHA384 - AES256-SHA Supported IANA/RFC aliases: - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 - TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 - TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 - TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA - TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA - TLS_RSA_WITH_AES_128_GCM_SHA256 - TLS_RSA_WITH_AES_128_CBC_SHA - TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA - TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA - TLS_RSA_WITH_AES_256_GCM_SHA384 - TLS_RSA_WITH_AES_256_CBC_SHA In non-FIPS Envoy Proxy builds the default cipher list is: - [ECDHE-ECDSA-AES128-GCM-SHA256|ECDHE-ECDSA-CHACHA20-POLY1305] - [ECDHE-RSA-AES128-GCM-SHA256|ECDHE-RSA-CHACHA20-POLY1305] - ECDHE-ECDSA-AES256-GCM-SHA384 - ECDHE-RSA-AES256-GCM-SHA384 In builds using BoringSSL FIPS the default cipher list is: - ECDHE-ECDSA-AES128-GCM-SHA256 - ECDHE-RSA-AES128-GCM-SHA256 - ECDHE-ECDSA-AES256-GCM-SHA384 - ECDHE-RSA-AES256-GCM-SHA384
ecdhCurves
string array
false
ECDHCurves specifies the set of supported ECDH curves. In non-FIPS Envoy Proxy builds the default curves are: - X25519 - P-256 In builds using BoringSSL FIPS the default curve is: - P-256
signatureAlgorithms
string array
false
SignatureAlgorithms specifies which signature algorithms the listener should support.
ALPNProtocols supplies the list of ALPN protocols that should be exposed by the listener or used by the proxy to connect to the backend. Defaults: 1. HTTPS Routes: h2 and http/1.1 are enabled in listener context. 2. Other Routes: ALPN is disabled. 3. Backends: proxy uses the appropriate ALPN options for the backend protocol. When an empty list is provided, the ALPN TLS extension is disabled. Defaults to [h2, http/1.1] if not specified. Typical Supported values are: - http/1.0 - http/1.1 - h2
Fingerprints specifies TLS client fingerprinting. When specified, a JAX fingerprint derived from the client’s TLS handshake is generated. The fingerprint can be logged in access logs or forwarded to upstream services using request headers. Fingerprinting is disabled if not specified. Supported values are: - JA3 - JA4
Namespaces determines which namespaces are considered for target selection. If unspecified, only targets in the same namespace as this policy are considered. When specified, the effective set of namespaces is always constrained to the namespaces watched by Envoy Gateway. Selecting targets across namespaces requires a ReferenceGrant in the target namespace that allows this policy kind to reference the selected target kind. Cross-namespace targets without a matching ReferenceGrant are ignored.
matchLabels
object (keys:string, values:string)
false
MatchLabels are the set of label selectors for identifying the targeted resource.
From indicates how namespaces are selected for this target selector. All means all namespaces watched by Envoy Gateway. Selector means namespaces watched by Envoy Gateway that match Selector.
ClientSamplingFraction represents the fraction of requests that should be selected for tracing when requested by the client. If unspecified, client-forced tracing is disabled by default and users must set this field to opt in.
CustomTags defines the custom tags to add to each span. If provider is kubernetes, pod name and namespace are added by default. Deprecated: Use Tags instead.
tags
object (keys:string, values:string)
false
Tags defines the custom tags to add to each span. Envoy command operators may be used in the value. The format string documentation provides more information. If provider is kubernetes, pod name and namespace are added by default. Same keys take precedence over CustomTags.
SpanName defines the name of the span which will be used for tracing. Envoy command operators may be used in the value. The format string documentation provides more information. If not set, the span name is provider specific. e.g. Datadog use ingress as the default client span name, and router <UPSTREAM_CLUSTER> egress as the server span name.
TracingProvider
TracingProvider defines the tracing provider configuration.
BackendRef references a Kubernetes object that represents the backend server to which the authorization request will be sent. Deprecated: Use BackendRefs instead. This field will be removed in v1.11.
Host define the provider service hostname. Deprecated: Use BackendRefs instead. This field will be removed in v1.11.
port
integer
false
4317
Port defines the port the provider service is exposed on. Deprecated: Use BackendRefs instead. This field will be removed in v1.11.
serviceName
string
false
ServiceName defines the service name to use in tracing configuration. If not set, Envoy Gateway will use a default service name set as “name.namespace” (e.g., “my-gateway.default”). Note: This field is only supported for OpenTelemetry and Datadog tracing providers. For Zipkin, the service name in traces is always derived from the Envoy –service-cluster flag (typically “namespace/name” format). Setting this field has no effect for Zipkin.
The upstream server responds with any 5xx response code, or does not respond at all (disconnect/reset/read timeout). Includes connect-failure and refused-stream.
gateway-error
The response is a gateway error (502,503 or 504).
reset
The upstream server does not respond at all (disconnect/reset/read timeout.)
reset-before-request
Like reset, but only retry if the request headers have not been sent to the upstream server.
connect-failure
Connection failure to the upstream server (connect timeout, etc.). (Included in 5xx)
retriable-4xx
The upstream server responds with a retriable 4xx response code. Currently, the only response code in this category is 409.
refused-stream
The upstream server resets the stream with a REFUSED_STREAM error code.
retriable-status-codes
The upstream server responds with any response code matching one defined in the RetriableStatusCodes.
cancelled
The gRPC status code in the response headers is “cancelled”.
deadline-exceeded
The gRPC status code in the response headers is “deadline-exceeded”.
internal
The gRPC status code in the response headers is “internal”.
resource-exhausted
The gRPC status code in the response headers is “resource-exhausted”.
unavailable
The gRPC status code in the response headers is “unavailable”.
Name is a unique name for this Wasm extension. It is used to identify the Wasm extension if multiple extensions are handled by the same vm_id and root_id. It’s also used for logging/debugging. If not specified, EG will generate a unique name for the Wasm extension. When Code is omitted, Name is required and must match a module registered in EnvoyProxy.spec.wasmModules.
VMSharingScope defines the scope within which this extension may share a Wasm VM. If Policy or unset, each policy’s Wasm entry uses its own VM ID. The same entry may reuse its VM across routes; different entries do not share a VM. If Namespace, this extension may share a VM with other extensions that specify Namespace in the same EnvoyExtensionPolicy namespace. Envoy determines VM compatibility using the Wasm code and VM configuration, including environment variables. Each Envoy worker has its own VM. Sharing a VM shares module-level state and VM failures. Plugin names and root IDs are not changed; matching plugin identities may also share a root context.
rootID
string
true
RootID is a unique ID for a set of extensions in a VM which will share a RootContext and Contexts if applicable (e.g., an Wasm HttpFilter and an Wasm AccessLog). If left blank, all extensions with a blank root_id with the same vm_id will share Context(s). Note: RootID must match the root_id parameter used to register the Context in the Wasm code.
Config is the configuration for the Wasm extension. This configuration will be passed as a JSON string to the Wasm extension.
failOpen
boolean
false
false
FailOpen is a switch used to control the behavior when a fatal error occurs during the initialization or the execution of the Wasm extension. If FailOpen is set to true, the system bypasses the Wasm extension and allows the traffic to pass through. If it is set to false or not set (defaulting to false), the system blocks the traffic and returns an HTTP 5xx error. If set to true, the Wasm extension will also be bypassed if the configuration is invalid.
PullPolicy is the policy to use when pulling the Wasm module by either the HTTP or Image source. This field is only applicable when the SHA256 field is not set. If not specified, the default policy is IfNotPresent except for OCI images whose tag is latest. Note: EG does not update the Wasm module every time an Envoy proxy requests the Wasm module even if the pull policy is set to Always. It only updates the Wasm module when the EnvoyExtension resource version changes.
WasmCodeSourceTLSConfig
WasmCodeSourceTLSConfig defines the TLS configuration when connecting to the Wasm code source.
CACertificateRef contains a reference to Kubernetes objects that contain TLS certificates of the Certificate Authorities that can be used as a trust anchor to validate the certificates presented by the Wasm code source. Kubernetes ConfigMap, Kubernetes Secret, and Kubernetes ClusterTrustBundle are supported.
WasmCodeSourceType
Underlying type:string
WasmCodeSourceType specifies the types of sources for the Wasm code.
HostKeys is a list of keys for environment variables from the host envoy process that should be passed into the Wasm VM. This is useful for passing secrets to to Wasm extensions.
WasmModuleEntry
WasmModuleEntry defines a Wasm module that is registered and allowed for use
by EnvoyExtensionPolicy resources.
WasmVMSharingScopePolicy gives each policy’s Wasm entry its own VM ID. The same entry may reuse its VM across routes; different entries do not share a VM.
Namespace
WasmVMSharingScopeNamespace allows compatible extensions that specify this scope in the same EnvoyExtensionPolicy namespace to share a VM.
WeightedZoneConfig
WeightedZoneConfig defines the weight for a specific locality zone.
Zone specifies the topology zone this weight applies to. The value should match the topology.kubernetes.io/zone label of the nodes where endpoints are running. Zones not listed in the configuration receive a default weight of 1.
weight
integer
true
Weight defines the weight for this locality. Higher values receive more traffic. The actual traffic distribution is proportional to this value relative to other localities.
WithUnderscoresAction
Underlying type:string
WithUnderscoresAction configures the action to take when an HTTP header with underscores
is encountered.
WithUnderscoresActionAllow allows headers with underscores to be passed through.
RejectRequest
WithUnderscoresActionRejectRequest rejects the client request. HTTP/1 requests are rejected with the 400 status. HTTP/2 requests end with the stream reset.
DropHeader
WithUnderscoresActionDropHeader drops the client header with name containing underscores. The header is dropped before the filter chain is invoked and as such filters will not see dropped headers.
XDSServer
XDSServer defines configuration values for the xDS gRPC server.
MaxConnectionAge is the maximum age of an active connection before Envoy Gateway will initiate a graceful close. If unspecified, Envoy Gateway randomly selects a value between 10h and 12h to stagger reconnects across replicas.
MaxConnectionAgeGrace is the grace period granted after reaching MaxConnectionAge before the connection is forcibly closed. The default grace period is 2m.
MaxReceiveMessageSize defines the maximum size of a single xDS message that the xDS gRPC server will accept from an Envoy proxy. Envoy’s requests grow with the number of resources it holds: on every stream (re)connect, the first delta xDS request for each resource type echoes back the name and version of every resource the proxy currently has. At a large enough scale this exceeds the 4MiB default, and the stream fails immediately with “received message larger than max”, leaving the proxy stuck on its last known-good configuration. Note this limit applies only to what Envoy Gateway receives; the configuration it sends to Envoy is not bounded by it. If unspecified, defaults to 32MiB.
XDSTranslatorHook
Underlying type:string
XDSTranslatorHook defines the types of hooks that an Envoy Gateway extension may support
for the xds-translator
XFCCForwardModeSanitize removes the XFCC header from the request. This is the default mode.
ForwardOnly
XFCCForwardModeForwardOnly forwards the XFCC header in the request if the client connection is mTLS.
AppendForward
XFCCForwardModeAppendForward appends the client certificate information to the request’s XFCC header and forward it if the client connection is mTLS.
SanitizeSet
XFCCForwardModeSanitizeSet resets the XFCC header with the client certificate information and forward it if the client connection is mTLS. The existing certificate information in the XFCC header is removed.
AlwaysForwardOnly
XFCCForwardModeAlwaysForwardOnly always forwards the XFCC header in the request, regardless of whether the client connection is mTLS.
XForwardedClientCert
XForwardedClientCert configures how Envoy Proxy handle the x-forwarded-client-cert (XFCC) HTTP header.
CertDetailsToAdd specifies the fields in the client certificate to be forwarded in the XFCC header. Hash(the SHA 256 digest of the current client certificate) and By(the Subject Alternative Name) are always included if the client certificate is forwarded. This field is only applicable when the mode is set to AppendForward or SanitizeSet and the client connection is mTLS.
NumTrustedHops specifies how many trusted hops to count from the rightmost side of the X-Forwarded-For (XFF) header when determining the original client’s IP address. If NumTrustedHops is set to N, the client IP is taken from the Nth address from the right end of the XFF header. Example: XFF = “203.0.113.128, 203.0.113.10, 203.0.113.1” NumTrustedHops = 2 → Trusted client address = 203.0.113.10 Only one of NumTrustedHops or TrustedCIDRs should be configured.
TrustedCIDRs is a list of CIDR ranges to trust when evaluating the remote IP address to determine the original client’s IP address. When the remote IP address matches a trusted CIDR and the x-forwarded-for header was sent, each entry in the x-forwarded-for header is evaluated from right to left and the first public non-trusted address is used as the original client address. If all addresses in x-forwarded-for are within the trusted list, the first (leftmost) entry is used. Only one of NumTrustedHops and TrustedCIDRs must be set.
disableXForwardedForAppend
boolean
false
DisableXForwardedForAppend configures Envoy Proxy to stop appending the downstream address to the X-Forwarded-For header. This only disables the automatic append behavior. It does not remove or sanitize an incoming X-Forwarded-For header.
XRateLimitHeadersOption
Underlying type:string
XRateLimitHeadersOption controls whether X-RateLimit response headers are sent for a rate limit rule.
Valid values are “Off” and “DraftVersion03”.
This allows per-rule override of the global X-RateLimit header setting in ClientTrafficPolicy.
XRateLimitHeadersOptionDisabled disables X-RateLimit headers for this rate limit rule, regardless of the global ClientTrafficPolicy setting.
DraftVersion03
XRateLimitHeadersOptionDraftVersion03 enables X-RateLimit headers using RFC draft version 03 for this rate limit rule, regardless of the global ClientTrafficPolicy setting.
ZipkinTraceContextMode
Underlying type:string
ZipkinTraceContextMode defines the trace context headers used by the Zipkin tracer.
ZipkinTraceContextModeUseB3 uses B3 headers only, for both extraction and injection.
UseB3WithW3CPropagation
ZipkinTraceContextModeUseB3WithW3CPropagation uses both B3 and W3C trace context headers. Extraction: prefers B3 headers, falling back to the W3C traceparent header if B3 headers are absent. Injection: emits both B3 and W3C traceparent headers.
ZipkinTracingProvider
ZipkinTracingProvider defines the Zipkin tracing provider configuration.
Enable128BitTraceID determines whether a 128bit trace id will be used when creating a new trace instance. If set to false, a 64bit trace id will be used.
disableSharedSpanContext
boolean
false
DisableSharedSpanContext determines whether the default Envoy behaviour of client and server spans sharing the same span context should be disabled.
TraceContextMode determines which trace context headers are used to extract the trace context from downstream requests and to inject it into upstream requests. Defaults to UseB3.
ZoneAware
ZoneAware defines the configuration related to the distribution of requests between locality zones.
WeightedZones configures weight-based traffic distribution across locality zones. Traffic is distributed proportionally based on the sum of all zone weights.
ZstdCompressionStrategy
Underlying type:string
ZstdCompressionStrategy defines the compression strategies supported by the Zstd compressor.
The higher the value of the selected strategy, the more complex it is, resulting in stronger
and slower compression.
CompressionLevel sets the compression parameters according to the pre-defined zstd compression level table, from 1 to 22. Note that the exact compression parameters are dynamically determined, depending on both compression level and source content size (when known). If not set, defaults to 3.
enableChecksum
boolean
false
EnableChecksum specifies whether a 32-bits checksum of the content is written at the end of the frame. If not set, defaults to false.
Strategy selects the zstd compression strategy. The higher the value of the selected strategy, the more complex it is, resulting in stronger and slower compression. If not set, defaults to Default.
chunkSize
integer
false
ChunkSize is the size in bytes of the compressor’s next output buffer, from 4096 to 65536. If not set, defaults to 4096.
5.2 - Kubernetes Gateway API
This section includes APIs of Kubernetes Gateway API.
5.2.1 - BackendTLSPolicy
The BackendTLSPolicy resource is GA and has been part of the Standard
Channel since v1.4.0. For more information on release channels, refer
to our versioning guide.
BackendTLSPolicy is a Gateway API type for specifying the TLS configuration
of the connection from the Gateway to a backend pod(s) via the Service API object.
Implementations may also decide to support the usage of BackendTLSPolicy for specifying the TLS configuration
of the connection from the Gateway to services not connected via HTTPRoute, and any
other kind of backend like InferencePool
Background
BackendTLSPolicy specifically addresses the configuration of TLS in order to convey HTTPS from the Gateway
dataplane to the backend. This is referred to as “backend TLS termination” and enables the Gateway to know
how to connect to a backend pod that has its own certificate.
While there are other API objects provided for TLS to be configured for passthrough and edge termination,
this API object allows users to specifically configure backend TLS termination. For more information on TLS
configuration in Gateway API, see TLS Configuration.
BackendTLSPolicy is a Direct PolicyAttachment without defaults or overrides,
applied to a Service that accesses a backend, where the BackendTLSPolicy resides in the same namespace as the
Service to which it is applied. The BackendTLSPolicy and the Service must reside in the same namespace in order
to prevent the complications involved with sharing trust across namespace boundaries.
Additionally, implementations may use BackendTLSPolicy for specifying the TLS configuration
of the connection from the Gateway to services not connected via HTTPRoute, and any other
kind of backend, but this behavior is optional and may not be available on all implementations.
All Gateway API Routes that point to a referenced Service should respect a configured BackendTLSPolicy.
TargetRefs - Defines the targeted API object of the policy.
Validation - Defines the configuration for TLS, including hostname, CACertificateRefs, and
WellKnownCACertificates.
Hostname - Defines the Server Name Indication (SNI) that the Gateway uses to connect to the backend.
SubjectAltNames - Specifies one or more Subject Alternative Names that the backend certificate must match. When specified, the certificate must have at least one matching SAN. This field enables separation between SNI (hostname) and certificate identity validation. A maximum of 5 SANs are allowed.
CACertificateRefs - Defines one or more references to objects that contain PEM-encoded TLS certificates,
which are used to establish a TLS handshake between the Gateway and backend Pod. Either CACertificateRefs or
WellKnownCACertificates may be specified, but not both.
WellKnownCACertificates - Specifies whether system CA certificates may be used in the TLS
handshake between the Gateway and backend Pod. Either CACertificateRefs or WellKnownCACertificates may be specified, but not both.
Options - A map of key/value pairs enabling extended TLS configuration for implementations that choose to provide support. Check your implementation’s documentation for details.
The following chart outlines the object definitions and relationship:
While the diagram above shows an HTTPRoute, BackendTLSPolicy is a
union feature and
works with any route type that forwards traffic to backends, including
GRPCRoute and TLSRoute (when in Terminate mode).
Targeting backends
A BackendTLSPolicy targets a backend Pod (or set of Pods) via one or more TargetRefs to a Service. This TargetRef is a
required object reference that specifies a Service by its Name, Kind (Service), and optionally its Namespace and Group.
TargetRefs identify the Service(s) for which your Route requires TLS.
Cross-namespace certificate references are not allowed.
BackendTLSPolicyValidation
A BackendTLSPolicyValidation is the specification for the BackendTLSPolicy and defines the configuration for TLS,
including hostname (for server name indication) and certificates.
Hostname
Hostname defines the server name indication (SNI) the Gateway should use in order to connect to the backend, and must
match the certificate served by the backend pod. A hostname is the fully qualified domain name of a network host, as
defined by RFC 3986. Note the following deviations from the “host” part of the URI as defined in the RFC:
IP addresses are not allowed.
Also note:
Wildcard hostnames are not allowed.
Subject Alternative Names
This field was added to BackendTLSPolicy in v1.2.0
The subjectAltNames field enables basic mutual TLS configuration between Gateways and backends, as well as the optional use of SPIFFE. When subjectAltNames is specified, the certificate served by the backend must have at least one Subject Alternative Name matching one of the specified values. This is particularly useful for SPIFFE implementations where URI-based SANs may not be valid SNIs. Subject Alternative Names may contain one of either a Hostname or URI field, and must contain a Type specifying whether Hostname or URI is chosen.
IP addresses and wildcard hostnames are not allowed. (see the description for Hostname above for more details).
Hostname: DNS name format
URI: URI format (e.g., SPIFFE ID)
TLS Options
This field was added to BackendTLSPolicy in v1.2.0
The options field allows specification of implementation-specific TLS configurations. This can include:
Check your implementation documentation for details.
Certificates
The BackendTLSPolicyValidation must contain a certificate reference of some kind, and contains two ways to configure the
certificate to use for backend TLS, CACertificateRefs and WellKnownCACertificates. Only one of these may be used per
BackendTLSPolicyValidation.
CACertificateRefs
CACertificateRefs refer to one or more PEM-encoded TLS certificates.
Cross-namespace certificate references are not allowed.
WellKnownCACertificates
If you are working in an environment where specific TLS certificates are not required, and your Gateway API
implementation allows system or default certificates to be used, e.g. in a development environment, you may
set WellKnownCACertificates to “System” to tell the Gateway to use a set of trusted CA Certificates. There may be
some variation in which system certificates are used by each implementation. Refer to documentation from your
implementation of choice for more information.
PolicyStatus
Status defines the observed state of the BackendTLSPolicy and is not user-configurable. Check status in the same
way you do for other Gateway API objects to verify correct operation. Note that the status in BackendTLSPolicy
uses PolicyAncestorStatus to allow you to know which parentReference set that particular status.
5.2.2 - Gateway
The Gateway resource is GA and has been part of the Standard Channel since
v0.5.0. For more information on release channels, refer to our versioning
guide.
A Gateway is 1:1 with the lifecycle of the configuration of infrastructure.
When a user creates a Gateway, some load balancing infrastructure is
provisioned or configured (see below for details) by the GatewayClass
controller. Gateway is the resource that triggers actions in this API. Other
resources in this API are configuration snippets until a Gateway has been
created to link the resources together.
The Gateway spec defines the following:
GatewayClassName- Defines the name of a GatewayClass object used by
this Gateway.
Listeners- Define the hostnames, ports, protocol, termination, TLS
settings and which routes can be attached to a listener.
Addresses- Define the network addresses requested for this gateway.
If the desired configuration specified in Gateway spec cannot be achieved, the
Gateway will be in an error state with details provided by status conditions.
Deployment models
Depending on the GatewayClass, the creation of a Gateway could do any of
the following actions:
Use cloud APIs to create an LB instance.
Spawn a new instance of a software LB (in this or another cluster).
Add a configuration stanza to an already instantiated LB to handle the new
routes.
Program the SDN to implement the configuration.
Something else we haven’t thought of yet…
The API does not specify which one of these actions will be taken.
Gateway Status
GatewayStatus is used to surface the status of a Gateway relative to the
desired state represented in spec. GatewayStatus consists of the following:
Addresses- Lists the IP addresses that have actually been bound to the
Gateway.
Listeners- Provide status for each unique listener defined in spec.
Conditions- Describe the current status conditions of the Gateway.
Both Conditions and Listeners.conditions follow the conditions pattern used
elsewhere in Kubernetes. This is a list that includes a type of condition, the
status of the condition and the last time this condition changed.
5.2.3 - GatewayClass
The GatewayClass resource is GA and has been part of the Standard Channel since
v0.5.0. For more information on release channels, refer to our versioning
guide.
GatewayClass is cluster-scoped resource defined by the
infrastructure provider. This resource represents a class of Gateways that can
be instantiated.
We expect that one or more GatewayClasses will be created by the
infrastructure provider for the user. It allows decoupling of which mechanism
(e.g. controller) implements the Gateways from the user. For instance, an
infrastructure provider may create two GatewayClasses named internet and
private to reflect Gateways that define Internet-facing vs private, internal
applications.
The user of the classes will not need to know howinternet and private are
implemented. Instead, the user will only need to understand the resulting
properties of the class that the Gateway was created with.
GatewayClass parameters
Providers of the Gateway API may need to pass parameters to their controller
as part of the class definition. This is done using the
GatewayClass.spec.parametersRef field:
# GatewayClass for Gateways that define Internet-facing applications.kind:GatewayClassmetadata:name:internetspec:controllerName:"example.net/gateway-controller"parametersRef:group:example.netkind:Configname:internet-gateway-config---apiVersion:example.net/v1alpha1kind:Configmetadata:name:internet-gateway-configspec:ip-address-pool:internet-vips...
Using a Custom Resource for GatewayClass.spec.parametersRef is encouraged
but implementations may resort to using a ConfigMap if needed.
GatewayClass status
GatewayClasses MUST be validated by the provider to ensure that the configured
parameters are valid. The validity of the class will be signaled to the user via
GatewayClass.status:
A new GatewayClass will start with the Accepted condition set to
False. At this point the controller has not seen the configuration. Once the
controller has processed the configuration, the condition will be set to
True:
If there is an error in the GatewayClass.spec, the conditions will be
non-empty and contain information about the error.
kind:GatewayClass...status:conditions:- type:Acceptedstatus:FalseReason:BadFooBarMessage:"foobar"is an FooBar.
GatewayClass controller selection
The GatewayClass.spec.controller field determines the controller implementation
responsible for managing the GatewayClass. The format of the field is opaque
and specific to a particular controller. The GatewayClass selected by a given
controller field depends on how various controller(s) in the cluster interpret
this field.
It is RECOMMENDED that controller authors/deployments make their selection
unique by using a domain / path combination under their administrative control
(e.g. controller managing of all controllers starting with example.net is the
owner of the example.net domain) to avoid conflicts.
Controller versioning can be done by encoding the version of a controller into
the path portion. An example scheme could be (similar to container URIs):
example.net/gateway/v1 // Use version 1
example.net/gateway/v2.1 // Use version 2.1
example.net/gateway // Use the default version
5.2.4 - GRPCRoute
The GRPCRoute resource is GA and has been part of the Standard Channel since
v1.1.0. For more information on release channels, refer to our versioning
guide.
If you know you’re working with gRPC, prefer using a GRPCRoute. An HTTPRoute may be sufficient
for basic routing and load balancing, but GRPCRoute makes the intent clearer and can unlock
more gRPC-specific functionality. See When to Use GRPCRoute.
GRPCRoute is a Gateway API type for specifying routing behavior
of gRPC requests from a Gateway listener to an API object, i.e. Service.
Background
While it is possible to route gRPC with HTTPRoutes or via custom, out-of-tree
CRDs, in the long run, this leads to a fragmented ecosystem.
Given gRPC’s importance in the application-layer networking space and to
the Kubernetes project in particular, the determination was made not to allow
the ecosystem to fragment unnecessarily.
Encapsulated Network Protocols
In general, when it is possible to route an encapsulated protocol at a lower
level, it is acceptable to introduce a route resource at the higher layer when
the following criteria are met:
Users of the encapsulated protocol would miss out on significant conventional features from their ecosystem if forced to route at a lower layer.
Users of the encapsulated protocol would experience a degraded user experience if forced to route at a lower layer.
The encapsulated protocol has a significant user base, particularly in the Kubernetes community.
gRPC meets all of these criteria, so the decision was made to include GRPCRoutein Gateway API.
Cross Serving
In general, it is recommended that separate hostnames be used for gRPC and
non-gRPC HTTP traffic. This aligns with standard practice in the gRPC community.
Implementations that support GRPCRoute may enforce uniqueness of
hostnames between GRPCRoutes and HTTPRoutes. That is, if a route (A) of type HTTPRoute or
GRPCRoute is attached to a Listener and that listener already has another Route (B) of
the other type attached and the intersection of the hostnames of A and B is
non-empty, then the implementation may reject Route A and raise an ‘Accepted’ condition with a status of ‘False’ in
the corresponding RouteParentStatus.
If there is a necessity to serve HTTP and gRPC on the same hostname with
the only differentiator being URI, and the implementation enforces uniqueness, the user should use HTTPRoute resources
for both gRPC and HTTP. This will come at the cost of the improved UX of the GRPCRoute resource.
When to Use GRPCRoute
gRPC traffic can be routed with either HTTPRoute or GRPCRoute. For basic
gRPC load balancing, GRPCRoute is not technically required because HTTPRoute
can do it. The following guidance helps you choose the right resource for your
use case.
When HTTPRoute Is Sufficient
HTTPRoute is sufficient when you only need basic routing and load balancing
for gRPC traffic without gRPC-specific features. Use HTTPRoute when:
You need simple hostname- or path-based routing and load balancing only.
You do not need gRPC-aware retries or metrics (e.g. retries on gRPC status codes, gRPC-oriented metrics).
You must serve HTTP and gRPC on the same hostname with URI as the only
differentiator; in that case you must use HTTPRoute for both (see Cross
Serving above).
With HTTPRoute, gRPC methods are matched by specifying the gRPC path as a
URI path (e.g. /package.Service/Method). With GRPCRoute, you match by
service and method fields (e.g. service: com.example.User, method: Login).
When to Prefer GRPCRoute
Prefer GRPCRoute when you need gRPC-specific behavior or better ergonomics
for gRPC users. Use GRPCRoute when:
You want to match by gRPC service and method names directly (e.g.
service: com.example.User, method: Login) instead of URI paths.
You need gRPC-aware policies such as retries conditioned on gRPC status
codes (e.g. CANCELLED, RESOURCE_EXHAUSTED).
You need gRPC-oriented metrics or observability from the implementation.
Guidance for Controller Implementers
Controllers that generate Routes on behalf of users (e.g. higher-level APIs
that create Gateway API routes) should consider the following:
If you generate HTTPRoute for basic gRPC load balancing, consider
offering a GRPCRoute option so that users who need gRPC-specific features
can use them without switching to manually managing routes.
Do not add gRPC-specific policy (such as retries on gRPC status codes) to
HTTPRoute. Keep gRPC-aware configuration in GRPCRoute only.
Spec
The specification of a GRPCRoute consists of:
ParentRefs- Define which Gateways this Route wants to be attached
to.
Hostnames (optional)- Define a list of hostnames to use for
matching the Host header of gRPC requests.
Rules- Define a list of rules to perform actions against
matching gRPC requests. Each rule consists of matches,
filters (optional), backendRefs (optional), and
name (optional) fields.
The following illustrates a GRPCRoute that sends all traffic to one Service:
Attaching to Gateways
Each Route includes a way to reference the parent resources it wants to attach
to. In most cases, that’s going to be Gateways, but there is some flexibility
here for implementations to support other types of parent resources.
The following example shows how a Route would attach to the acme-lb Gateway:
Note that the target Gateway needs to allow GRPCRoutes from the route’s
namespace to be attached for the attachment to be successful.
Hostnames
Hostnames define a list of hostnames to match against the Host header of the
gRPC request. When a match occurs, the GRPCRoute is selected to perform request
routing based on rules and filters (optional). A hostname is the fully qualified
domain name of a network host, as defined by RFC 3986. Note the
following deviations from the “host” part of the URI as defined in the RFC:
IPs are not allowed.
The : delimiter is not respected because ports are not allowed.
Incoming requests are matched against hostnames before the GRPCRoute rules are
evaluated. If no hostname is specified, traffic is routed based on GRPCRoute
rules and filters (optional).
The following example defines hostname “my.example.com”:
Rules define semantics for matching an gRPC requests based on conditions,
optionally executing additional processing steps, and optionally forwarding
the request to an API object.
Matches
Matches define conditions used for matching an gRPC requests. Each match is
independent, i.e. this rule will be matched if any single match is satisfied.
Take the following matches configuration as an example:
For a request to match against this rule, it must satisfy EITHER of the
following conditions:
The com.example.User.Login method AND contains the header “version: 2”
The com.example.v2.User.Login method.
If no matches are specified, the default is to match every gRPC request.
Filters (optional)
Filters define processing steps that must be completed during the request or
response lifecycle. Filters act as an extension point to express additional
processing that may be performed in Gateway implementations. Some examples
include request or response modification, implementing authentication
strategies, rate-limiting, and traffic shaping.
The following example adds header “my-header: foo” to gRPC requests with Host
header “my.filter.com”. Note that GRPCRoute uses HTTPRoute filters for features
with functionality identical to HTTPRoute, such as this.
API conformance is defined based on the filter type. The effects of ordering
multiple behaviors are currently unspecified. This may change in the future
based on feedback during the alpha stage.
Conformance levels are defined by the filter type:
All “core” filters MUST be supported by implementations supporting GRPCRoute.
Implementers are encouraged to support “extended” filters.
“Implementation-specific” filters have no API guarantees across implementations.
Specifying a core filter multiple times has unspecified or custom conformance.
If an implementation cannot support a combinations of filters, they must clearly
document that limitation. In cases where incompatible or unsupported
filters are specified and cause the Accepted condition to be set to status
False, implementations may use the IncompatibleFilters reason to specify
this configuration error.
BackendRefs (optional)
BackendRefs defines the API objects to which matching requests should be sent. If
unspecified, the rule performs no forwarding. If unspecified and no filters
are specified that would result in a response being sent, an UNIMPLEMENTED error code
is returned.
The following example forwards gRPC requests for the method User.Login to service
“my-service1” on port 50051 and gRPC requests for the method Things.DoThing with
header magic: foo to service “my-service2” on port 50051:
apiVersion:gateway.networking.k8s.io/v1kind:GatewayClassmetadata:name:examplespec:controllerName:acme.io/gateway-controllerparametersRef:name:examplegroup:acme.iokind:Parameters---apiVersion:gateway.networking.k8s.io/v1kind:Gatewaymetadata:name:my-gatewayspec:gatewayClassName:examplelisteners:# Use GatewayClass defaults for listener definition.- name:httpsprotocol:HTTPSport:50051tls:certificateRefs:- kind:Secretgroup:""name:example-com-cert---apiVersion:gateway.networking.k8s.io/v1kind:GRPCRoutemetadata:name:grpc-app-1spec:parentRefs:- name:my-gatewayhostnames:- "example.com"rules:- matches:- method:service:com.example.Usermethod:LoginbackendRefs:- name:my-service1port:50051- matches:- headers:- type:Exactname:magicvalue:foomethod:service:com.example.Thingsmethod:DoThingbackendRefs:- name:my-service2port:50051
The following example uses the weight field to forward 90% of gRPC requests to
foo.example.com to the “foo-v1” Service and the other 10% to the “foo-v2”
Service:
Reference the backendRef API documentation for additional details
on weight and other fields.
Name (optional)
This concept has been part of the Experimental Channel since v1.2.0.
For more information on release channels, refer to our
versioning guide.
GRPCRoute Rules include an optional name field. The applications for the name of a route rule are implementation-specific. It can be used to reference individual route rules by name from other resources, such as in the sectionName field of metaresources (GEP-2648), in the status stanzas of resources related to the route object, to identify internal configuration objects generated by the implementation from GRPCRoute Rule, etc.
If specified, the value of the name field must comply with the SectionName type.
Status
Status defines the observed state of the GRPCRoute.
RouteStatus
RouteStatus defines the observed state that is required across all route types.
Parents
Parents define a list of the Gateways (or other parent resources) that are
associated with the GRPCRoute, and the status of the GRPCRoute with respect to
each of these Gateways. When a GRPCRoute adds a reference to a Gateway in
parentRefs, the controller that manages the Gateway should add an entry to this
list when the controller first sees the route and should update the entry as
appropriate when the route is modified.
Examples
The following example indicates GRPCRoute “grpc-example” has been accepted by
Gateway “gw-example” in namespace “gw-example-ns”:
Multiple GRPCRoutes can be attached to a single Gateway resource. Importantly,
only one Route rule may match each request. For more information on how conflict
resolution applies to merging, refer to the API specification.
5.2.5 - HTTPRoute
The HTTPRoute resource is GA and has been part of the Standard Channel since
v0.5.0. For more information on release channels, refer to our versioning
guide.
HTTPRoute is a Gateway API type for specifying routing behavior
of HTTP requests from a Gateway listener to an API object, i.e. Service.
Spec
The specification of an HTTPRoute consists of:
ParentRefs- Define which Gateways this Route wants to be attached
to.
Hostnames (optional)- Define a list of hostnames to use for
matching the Host header of HTTP requests.
Rules- Define a list of rules to perform actions against
matching HTTP requests. Each rule consists of matches,
filters (optional), backendRefs (optional),
timeouts (optional), and name (optional) fields.
The following illustrates an HTTPRoute that sends all traffic to one Service:
Attaching to Gateways
Each Route includes a way to reference the parent resources it wants to attach
to. In most cases, that’s going to be Gateways, but there is some flexibility
here for implementations to support other types of parent resources.
The following example shows how a Route would attach to the acme-lb Gateway:
Note that the target Gateway needs to allow HTTPRoutes from the route’s
namespace to be attached for the attachment to be successful.
You can also attach routes to specific sections of the parent resource.
For example, let’s say that the acme-lb Gateway includes the following
listeners:
You can bind a route to listener foo only, using the sectionName field
in parentRefs:
spec:parentRefs:- name:acme-lbsectionName:foo
Alternatively, you can achieve the same effect by using the port field,
instead of sectionName, in the parentRefs:
spec:parentRefs:- name:acme-lbport:8080
Binding to a port also allows you to attach to multiple listeners at once.
For example, binding to port 8090 of the acme-lb Gateway would be more
convenient than binding to the corresponding listeners by name:
However, when binding Routes by port number, Gateway admins will no longer have
the flexibility to switch ports on the Gateway without also updating the Routes.
The approach should only be used when a Route should apply to a specific port
number as opposed to listeners whose ports may be changed.
Hostnames
Hostnames define a list of hostnames to match against the Host header of the
HTTP request. When a match occurs, the HTTPRoute is selected to perform request
routing based on rules and filters (optional). A hostname is the fully qualified
domain name of a network host, as defined by RFC 3986. Note the
following deviations from the “host” part of the URI as defined in the RFC:
IPs are not allowed.
The : delimiter is not respected because ports are not allowed.
Incoming requests are matched against hostnames before the HTTPRoute rules are
evaluated. If no hostname is specified, traffic is routed based on HTTPRoute
rules and filters (optional).
The following example defines hostname “my.example.com”:
Rules define semantics for matching an HTTP request based on conditions,
optionally executing additional processing steps, and optionally forwarding
the request to an API object.
Matches
Matches define conditions used for matching an HTTP request. Each match is
independent, i.e. this rule will be matched if any single match is satisfied.
Take the following matches configuration as an example:
For a request to match against this rule, it must satisfy EITHER of the
following conditions:
A path prefixed with /foo AND contains the header “version: 2”
A path prefix of /v2/foo
If no matches are specified, the default is a prefix path match on “/”,
which has the effect of matching every HTTP request.
Filters (optional)
Filters define processing steps that must be completed during the request or
response lifecycle. Filters act as an extension point to express additional
processing that may be performed in Gateway implementations. Some examples
include request or response modification, implementing authentication
strategies, rate-limiting, and traffic shaping.
The following example adds header “my-header: foo” to HTTP requests with Host
header “my.filter.com”.
API conformance is defined based on the filter type. The effects of ordering
multiple behaviors is currently unspecified. This may change in the future
based on feedback during the alpha stage.
Conformance levels are defined by the filter type:
All “core” filters MUST be supported by implementations.
Implementers are encouraged to support “extended” filters.
“Implementation-specific” filters have no API guarantees across implementations.
Specifying a core filter multiple times has unspecified or
implementation-specific conformance.
All filters are expected to be compatible with each other except for the
URLRewrite and RequestRedirect filters, which may not be combined. If an
implementation cannot support other combinations of filters, they must clearly
document that limitation. In cases where incompatible or unsupported
filters are specified and cause the Accepted condition to be set to status
False, implementations may use the IncompatibleFilters reason to specify
this configuration error.
BackendRefs (optional)
BackendRefs defines API objects where matching requests should be sent. If
unspecified, the rule performs no forwarding. If unspecified and no filters
are specified that would result in a response being sent, a 500 error code
is returned.
The following example forwards HTTP requests for path prefix /bar to service
“my-service1” on port 8080, and HTTP requests fulfilling all four of the
following criteria
header magic: foo
query param great: example
path prefix /some/thing
method GET
to service “my-service2” on port 8080:
apiVersion:gateway.networking.k8s.io/v1kind:GatewayClassmetadata:name:examplespec:controllerName:acme.io/gateway-controllerparametersRef:name:examplegroup:acme.iokind:Parameters---apiVersion:gateway.networking.k8s.io/v1kind:Gatewaymetadata:name:my-gatewayspec:gatewayClassName:examplelisteners:# Use GatewayClass defaults for listener definition.- name:httpprotocol:HTTPport:80---apiVersion:gateway.networking.k8s.io/v1kind:HTTPRoutemetadata:name:http-app-1spec:parentRefs:- name:my-gatewayhostnames:- "foo.com"rules:- matches:- path:type:PathPrefixvalue:/barbackendRefs:- name:my-service1port:8080- matches:- headers:- type:Exactname:magicvalue:fooqueryParams:- type:Exactname:greatvalue:examplepath:type:PathPrefixvalue:/some/thingmethod:GETbackendRefs:- name:my-service2port:8080
The following example uses the weight field to forward 90% of HTTP requests to
foo.example.com to the “foo-v1” Service and the other 10% to the “foo-v2”
Service:
Reference the backendRef API documentation for additional details
on weight and other fields.
Timeouts (optional)
HTTPRoute timeouts have been part of the Standard Channel since v1.2.0.
For more information on release channels, refer to our
versioning guide.
HTTPRoute Rules include a Timeouts field. If unspecified, timeout behavior is implementation-specific.
There are 2 kinds of timeouts that can be configured in an HTTPRoute Rule:
request is the timeout for the Gateway API implementation to send a response to a client HTTP request. This timeout is intended to cover as close to the whole request-response transaction as possible, although an implementation MAY choose to start the timeout after the entire request stream has been received instead of immediately after the transaction is initiated by the client.
backendRequest is a timeout for a single request from the Gateway to a backend. This timeout covers the time from when the request first starts being sent from the gateway to when the full response has been received from the backend. This can be particularly helpful if the Gateway retries connections to a backend.
Because the request timeout encompasses the backendRequest timeout, the value of backendRequest must not be greater than the value of request timeout.
Timeouts are optional, and their fields are of type Duration. A zero-valued timeout (“0s”) MUST be interpreted as disabling the timeout. A valid non-zero-valued timeout MUST be >= 1ms.
The following example uses the request field which will cause a timeout if a client request is taking longer than 10 seconds to complete. The example also defines a 2s backendRequest which specifies a timeout for an individual request from the gateway to a backend service timeout-svc:
Reference the timeouts API documentation for additional details.
Name (optional)
This concept has been part of the Experimental Channel since v1.2.0.
For more information on release channels, refer to our
versioning guide.
HTTPRoute Rules include an optional name field. The applications for the name of a route rule are implementation-specific. It can be used to reference individual route rules by name from other resources, such as in the sectionName field of metaresources (GEP-2648), in the status stanzas of resources related to the route object, to identify internal configuration objects generated by the implementation from HTTPRoute Rule, etc.
If specified, the value of the name field must comply with the SectionName type.
The following example specifies the name field to identify HTTPRoute Rules used to split traffic between a read-only backend service and a write-only one:
This concept has been part of the Experimental Channel since v1.0.0.
For more information on release channels, refer to our
versioning guide.
Some implementations may require the backendRef to be labeled
explicitly in order to route traffic using a certain protocol. For Kubernetes
Service backends this can be done by specifying the appProtocol
field.
Status
Status defines the observed state of HTTPRoute.
RouteStatus
RouteStatus defines the observed state that is required across all route types.
Parents
Parents define a list of the Gateways (or other parent resources) that are
associated with the HTTPRoute, and the status of the HTTPRoute with respect to
each of these Gateways. When an HTTPRoute adds a reference to a Gateway in
parentRefs, the controller that manages the Gateway should add an entry to this
list when the controller first sees the route and should update the entry as
appropriate when the route is modified.
The following example indicates HTTPRoute “http-example” has been accepted by
Gateway “gw-example” in namespace “gw-example-ns”:
Multiple HTTPRoutes can be attached to a single Gateway resource. Importantly,
only one Route rule may match each request. For more information on how conflict
resolution applies to merging, refer to the API specification.
5.2.6 - ReferenceGrant
The ReferenceGrant resource is GA and has been part of the
Standard Channel since v0.6.0. For more information on release
channels, refer to our versioning guide.
This resource was originally named “ReferencePolicy”. It was renamed
to “ReferenceGrant” to avoid any confusion with policy attachment.
A ReferenceGrant can be used to enable cross namespace references within
Gateway API. In particular, Routes may forward traffic to backends in other
namespaces, or Gateways may refer to Secrets in another namespace.
In the past, we’ve seen that forwarding traffic across namespace boundaries is a
desired feature, but without a safeguard like ReferenceGrant,
vulnerabilities can
emerge.
If an object is referred to from outside its namespace, the object’s owner must
create a ReferenceGrant resource to explicitly allow that reference. Without a
ReferenceGrant, a cross namespace reference is invalid.
It is recommended that ReferenceGrants are used with caution, and that validations
and limits are applied by cluster admins to guarantee the proper usage of this resource.
Fundamentally a ReferenceGrant is made up of two lists, a list of resources
references may come from, and a list of resources that may be referenced.
The from list allows you to specify the group, kind, and namespace of
resources that may reference items described in the to list.
The to list allows you to specify the group and kind of resources that may be
referenced by items described in the from list. The namespace is not necessary
in the to list because a ReferenceGrant can only be used to allow references
to resources in the same namespace as the ReferenceGrant.
Example
The following example shows how an HTTPRoute in namespace foo can reference a
Service in namespace bar. In this example a ReferenceGrant in the bar
namespace explicitly allows references to Services from HTTPRoutes in the foo
namespace.
While the API is simplistic in nature, it comes with a few notable decisions:
Each ReferenceGrant only supports a single From and To section. Additional
trust relationships must be modeled with additional ReferenceGrant
resources.
Resource names are intentionally excluded from the “From” section of
ReferenceGrant because they rarely provide any meaningful protection. A user
that is able to write to resources of a certain kind within a namespace can
always rename resources or change the structure of the resources to match a
given grant.
A single Namespace is allowed per “From” struct. Although a selector would be
more powerful, it encourages unnecessarily insecure configuration.
The effect of these resources is purely additive, they stack on top of each
other. This makes it impossible for them to conflict with each other.
Please see the API
Specification
for more details on how specific ReferenceGrant fields are interpreted.
Implementation Guidelines
This API relies on runtime verification. Implementations MUST watch for changes
to these resources and recalculate the validity of cross-namespace references
after each change or deletion.
When communicating the status of a cross-namespace reference, implementations
MUST NOT expose information about the existence of a resource in another
namespace unless a ReferenceGrant exists allowing the reference to occur. This
means that if a cross-namespace reference is made without a ReferenceGrant to a
resource that doesn’t exist, any status conditions or warning messages need to
focus on the fact that a ReferenceGrant does not exist to allow this reference.
No hints should be provided about whether or not the referenced resource exists.
Exceptions
Cross namespace Route -> Gateway binding follows a slightly different pattern
where the handshake mechanism is built into the Gateway resource. For more
information on that approach, refer to the relevant Security Model
documentation. Although conceptually similar to
ReferenceGrant, this configuration is built directly into Gateway Listeners,
and allows for fine-grained per Listener configuration that would not be
possible with ReferenceGrant.
There are some situations where it MAY be acceptable to ignore ReferenceGrant
in favor of some other security mechanism. This MAY only be done if other
mechanisms like NetworkPolicy can effectively limit cross-namespace references
by the implementation.
An implementation choosing to make this exception MUST clearly document that
ReferenceGrant is not honored by their implementations and detail which
alternative safeguards are available. Note that this is unlikely to apply to
ingress implementations of the API and will not apply to all mesh
implementations.
For an example of the risks involved in cross-namespace references, refer to
CVE-2021-25740.
Implementations of this API need to be very careful to avoid confused deputy
attacks. ReferenceGrant provides a safeguard for that. Exceptions MUST only be
made by implementations that are absolutely certain that other equally effective
safeguards are in place.
Conformance Level
ReferenceGrant support is a “CORE” conformance level requirement for
cross-namespace references that originate from the following objects:
Gateway
GRPCRoute
HTTPRoute
TLSRoute
TCPRoute
UDPRoute
That is, all implementations MUST use this flow for any cross namespace
references in the Gateway and any of the core xRoute types, except as noted
in the Exceptions section above.
Other “ImplementationSpecific” objects and references MUST also use this flow
for cross-namespace references, except as noted in the Exceptions section above.
Potential Future API Group Change
ReferenceGrant is starting to gain interest outside of Gateway API and SIG
Network use cases. It is possible that this resource may move to a more neutral
home. Users of the ReferenceGrant API may be required to transition to a
different API Group (instead of gateway.networking.k8s.io) at some point in
the future.