From aadbbe460d588003343886f6a2c9c058590bc45d Mon Sep 17 00:00:00 2001 From: Jeff Boruszak <104028618+boruszak@users.noreply.github.com> Date: Wed, 17 May 2023 13:50:57 -0700 Subject: [PATCH] docs: Reference pages for service-router and service-resolver config entries (#17145) * service-resolve configuration entry reference * Updates * missing backtick * service router configuration entry reference * link fixes + tab fixes * link and tab fixes * link fixes * service resolver improvements * hierarchy fixes * spacing * links + formatting * proofing fixes * mmore fixes * Apply suggestions from code review suggestions from code review for service resolver Co-authored-by: trujillo-adam <47586768+trujillo-adam@users.noreply.github.com> * policy sections edits * service router code review * Tables to sections - service router HCL * YAML tables to sections * formatting fixes * converting tables to sections - service resolver * final tables to sections * Adjustments/alignments * nanosecond fix * Update website/content/docs/connect/config-entries/service-router.mdx Co-authored-by: trujillo-adam <47586768+trujillo-adam@users.noreply.github.com> * link to filter example config --------- Co-authored-by: trujillo-adam <47586768+trujillo-adam@users.noreply.github.com> --- .../config-entries/service-resolver.mdx | 1371 ++++++++++++- .../connect/config-entries/service-router.mdx | 1816 ++++++++++++----- 2 files changed, 2676 insertions(+), 511 deletions(-) diff --git a/website/content/docs/connect/config-entries/service-resolver.mdx b/website/content/docs/connect/config-entries/service-resolver.mdx index c8e98b6614d1..935ca4a6951b 100644 --- a/website/content/docs/connect/config-entries/service-resolver.mdx +++ b/website/content/docs/connect/config-entries/service-resolver.mdx @@ -1,40 +1,1247 @@ --- layout: docs -page_title: Service Resolver - Configuration Entry Reference -description: >- - The service resolver configuration entry kind defines subsets of service instances that satisfy upstream discovery requests. Use the reference guide to learn about `""service-resolver""` config entry parameters and how filtering by service subsets helps route traffic based on properties like version number. +page_title: Service Resolver Configuration Entry Reference +description: >- + Service resolver configuration entries are L7 traffic management tools for defining sets of service instances that resolve upstream requests and Consul’s behavior when resolving them. Learn how to write `service-resolver` config entries in HCL or YAML with a specification reference, configuration model, a complete example, and example code by use case. --- -# Service Resolver Configuration Entry +# Service resolver configuration entry reference + +This page provides reference information for service resolver configuration entries. Configure and apply service resolvers to create named subsets of service instances and define their behavior when satisfying upstream requests. + +Refer to [L7 traffic management overview](/consul/docs/connect/l7-traffic) for additional information. + +## Configuration model + +The following list outlines field hierarchy, language-specific data types, and requirements in the configuration entry. Click on a property name to view additional details, including default values. + + + + + +- [`Kind`](#kind): string | required | must be set to `service-resolver` +- [`Name`](#name): string | required +- [`Namespace`](#namespace): string | `default` +- [`Partition`](#partition): string | `default` +- [`Meta`](#meta): map +- [`ConnectTimeout`](#connecttimeout): string | `0s` +- [`RequestTimeout`](#requesttimeout): string | `15s` +- [`Subsets`](#subsets): map + - [`Filter`](#subsets): string + - [`OnlyPassing`](#subsets): boolean | `false` +- [`DefaultSubset`](#defaultsubset): string +- [`Redirect`](#redirect): map + - [`Service`](#redirect-service): string + - [`ServiceSubset`](#redirect-servicesubset): string + - [`Namespace`](#redirect-namespace): string + - [`Partition`](#redirect-partition): string | `default` + - [`Datacenter`](#redirect-datacenter): list + - [`Peer`](#redirect-peer): string +- [`Failover`](#failover): map + - [`Service`](#failover-service): string + - [`ServiceSubset`](#failover-servicesubset): string + - [`Namespace`](#failover-namespace): string + - [`Datacenters`](#failover-datacenters): list + - [`Targets`](#failover-targets): list + - [`Service`](#failover-targets-service): string + - [`ServiceSubset`](#failover-targets-servicesubset): string + - [`Namespace`](#failover-targets-namespace): string + - [`Partition`](#failover-targets-partition): string | `default` + - [`Datacenter`](#failover-targets-datacenter): string + - [`Peer`](#failover-targets-peer): string +- [`LoadBalancer`](#loadbalancer): map + - [`Policy`](#loadbalancer-policy): string + - [`LeastRequestConfig`](#loadbalancer-leastrequestconfig): map + - [`ChoiceCount`](#loadbalancer-leastrequestconfig-choicecount): integer | `2` + - [`RingHashConfig`](#loadbalancer-ringhashconfig): map + - [`MinimumRingSize`](#loadbalancer-ringhashconfig): integer | `1024` + - [`MaximumRingSize`](#loadbalancer-ringhashconfig): integer | `8192` + - [`HashPolicies`](#loadbalancer-hashpolicies): map + - [`Field`](#loadbalancer-hashpolicies-field): string + - [`FieldValue`](#loadbalancer-hashpolicies-fieldvalue): string + - [`CookieConfig`](#loadbalancer-hashpolicies-cookieconfig): map + - [`Session`](#loadbalancer-hashpolicies-cookieconfig-session): boolean | `false` + - [`TTL`](#loadbalancer-hashpolicies-cookieconfig-ttl): string + - [`Path`](#loadbalancer-hashpolicies-cookieconfig-path): string + - [`SourceIP`](#loadbalancer-hashpolicies-sourceip): boolean | `false` + - [`Terminal`](#loadbalancer-hashpolicies-terminal): boolean | `false` + + + + + +- [`apiVersion`](#apiversion): string | required | must be set to `consul.hashicorp.com/v1alpha1` +- [`kind`](#kind): string | required | must be set to `ServiceResolver` +- [`metadata`](#metadata): map | required + - [`name`](#metadata-name): string | required + - [`namespace`](#metadata-namespace): string | optional +- [`spec`](#spec): map | required + - [`connectTimeout`](#spec-connecttimeout): string | `0s` + - [`requestTimeout`](#spec-requesttimeout): string | `15s` + - [`subsets`](#spec-subsets): map + - [`filter`](#spec-subsets-filter): string + - [`onlyPassing`](#spec-subsets-onlypassing): boolean | `false` + - [`defaultSubset`](#spec-defaultsubset): string + - [`redirect`](#spec-redirect): map + - [`service`](#spec-redirect-service): string + - [`serviceSubset`](#spec-redirect-servicesubset): string + - [`namespace`](#spec-redirect-namespace): string + - [`partition`](#spec-redirect-partition): string + - [`datacenter`](#spec-redirect-datacenter): string + - [`peer`](#spec-redirect-peer): string + - [`failover`](#spec-failover): map + - [`service`](#spec-failover-service): string + - [`serviceSubset`](#spec-failover-servicesubset): string + - [`namespace`](#spec-failover-namespace): string + - [`datacenters`](#spec-failover-datacenters): string + - [`targets`](#spec-failover-targets): list + - [`service`](#spec-failover-targets-service): string + - [`serviceSubset`](#spec-failover-targets-servicesubset): string + - [`namespace`](#spec-failover-targets-namespace): string | `default` + - [`partition`](#spec-failover-targets-partition): string | `default` + - [`datacenter`](#spec-failover-targets-datacenter): string + - [`peer`](#spec-failover-targets-peer): string + - [`loadBalancer`](#spec-loadbalancer): map + - [`policy`](#spec-loadbalancer-policy): string + - [`leastRequestConfig`](#spec-loadbalancer-leastrequestconfig): map + - [`choiceCount`](#spec-loadbalancer-leastrequestconfig): integer | `2` + - [`ringHashConfig`](#spec-loadbalancer-ringhashconfig): map + - [`minimumRingSize`](#spec-loadbalancer-ringhashconfig): integer | `1024` + - [`maximumRingSize`](#spec-loadbalancer-ringhashconfig): integer | `8192` + - [`hashPolicies`](#spec-loadbalancer-hashpolicies): list + - [`field`](#spec-loadbalancer-hashpolicies-field): string + - [`fieldValue`](#spec-loadbalancer-hashpolicies-fieldvalue): string + - [`cookieConfig`](#spec-loadbalancer-hashpolicies-cookieconfig): map + - [`session`](#spec-loadbalancer-hashpolicies-cookieconfig-session): boolean | `false` + - [`ttl`](#spec-loadbalancer-hashpolicies-cookieconfig-ttl): string | `0s` + - [`path`](#spec-loadbalancer-hashpolicies-cookieconfig-path): string + - [`sourceIP`](#spec-loadbalancer-hashpolicies-sourceip): boolean | `false` + - [`terminal`](#spec-loadbalancer-hashpolicies-terminal): boolean | `false` + + + + +## Complete configuration + +When every field is defined, a service resolver configuration entry has the following form: + + + + --> **v1.8.4+:** On Kubernetes, the `ServiceResolver` custom resource is supported in Consul versions 1.8.4+.
-**v1.6.0+:** On other platforms, this config entry is supported in Consul versions 1.6.0+. +```hcl +Kind = "service-resolver" ## required +Name = "" +Namespace = "" +Partition = "" +Meta = { + = "" +} + +ConnectTimeout = "10s" +RequestTimeout = "15s" +Subsets = { + = { + Filter = "" + OnlyPassing = true + } + = { + Filter = "" + OnlyPassing = true + } +} +DefaultSubset = "" + +Redirect = { + Service = "" + ServiceSubset = "" + Namespace = "" + Partition = "" + Datacenter = "" + Peer = "" +} + +Failover = { ## requires at least one of the following: Service, ServiceSubset, Namespace, Targets, Datacenters + = { + Targets = [ + { Service = "" }, + { ServiceSubset = "" }, + { Namespace = "" }, + { Partition = "" }, + { Datacenter = "" }, + { Peer = "" } + ] + } + "*" = { + Service = "" + ServiceSubset = "" + Namespace = "" + Datacenters = ["", ""] + } +} + +LoadBalancer = { + Policy = "random" + LeastRequestConfig = { ## requires Policy = "least_request" + ChoiceCount = 2 + RingHashConfig = { ## requires Policy = "ring_hash" + MinimumRingSize = 1024 + MaximumRingSize = 8192 + } + } + HashPolicies = [ + { + Field = "header" ## cannot specify with SourceIP + FieldValue = "" ## cannot specify with SourceIP + CookieConfig = { + Session = false + TTL = "0s" + Path = "" + } + SourceIP = false ## cannot specify with Field or FieldValue + Terminal = false + } + ] +} + +``` + +
+ + + +```json +{ + "Kind":"service-resolver", // required + "Name":"", + "Namespace":"", + "Partition":"parition-configuration-applies-to>", + "Meta":{ + "":"" + }, + + "ConnectTimeout":"10s", + "RequestTimeout":"15s", + "Subsets":{ + "":{ + "Filter":"":{ + "Filter":"", + "OnlyPassing":true + } + }, + "DefaultSubset ":"", + + "Redirect":{ + "Service":"", + "ServiceSubset":"", + "Namespace":"", + "Partition":"", + "Datacenter":"", + "Peer":"" + }, + + "Failover":{ // requires at least one of the following": Service, ServiceSubset, Namespace, Targets, Datacenters + "":{ + "Targets":[ + {"Service":""}, + {"ServiceSubset":""}, + {"Namespace":""}, + {"Partition":""}, + {"Datacenter":""}, + {"Peer":""} + ] + }, + "*":{ + "Service ":"", + "ServiceSubset":"", + "Namespace":"", + "Datacenters":["", ""] + } + }, + + "LoadBalancer":{ + "Policy":"random", + "LeastRequestConfig":{ // requires Policy":"least_request" + "ChoiceCount":2 + }, + "RingHashConfig":{ // requires Policy":"ring_hash" + "MinimumRingSize":1024, + "MaximumRingSize":8192 + }, + "HashPolicies":[ + { + "Field":"header", // cannot specify with SourceIP + "FieldValue":"", // cannot specify with SourceIP + "CookieConfig":{ + "Session":false, + "TTL":"0s", + "Path":"" + }, + "SourceIP":false, // cannot specify with Field or FieldValue + "Terminal":false + } + ] + } +} +``` + + + + + +```yaml +apiVersion: consul.hashicorp.com/v1alpha1 # required +kind: ServiceResolver # required +metadata: + name: + namespace: +spec: + connectTimeout: 10s + requestTimeout: 15s + subsets: + : + filter: + onlyPassing: false + : + filter: + onlyPassing: false + defaultSubset: + redirect: + service: + servicesubset: + namespace: + partition: + peer: + failover: # requires at least one of the following: service, serviceSubset, namespace, targets, datacenters + : + targets: + - service: + - serviceSubset: + - namespace: + - partition: + - datacenter: + - peer: + `*`: + service: + serviceSubset: + namespace: + datacenters: ["", ""] + loadBalancer: + policy: random + leastRequestConfig: # requires policy: leastRequestConfig + choiceCount: 2 + ringHashConfig: # requires policy: ringHashConfig + minimumRingSize: 1024 + maximumRingSize: 8192 + hashPolicies: + - field: header # cannot specify with SourceIP + - fieldValue: # cannot specify with SourceIP + - cookieConfig: + session: false + ttl: 0s + path: + - sourceIP: false # cannot specify with field or fieldValue + - terminal: false +``` + + + +
+ +## Specification + +This section provides details about the fields you can configure in the configuration entry. + + + + + +### `Kind` + +Specifies the type of configuration entry to implement. Must be set to `service-resolver`. + +#### Values + +- Default: None +- This field is required. +- Data type: String value that must be set to `service-resolver`. + +### `Name` + +Specifies a name for the configuration entry. The name is metadata that you can use to reference the configuration entry when performing Consul operations, such as applying a configuration entry to a specific cluster. + +#### Values + +- Default: None +- This field is required. +- Data type: String + +### `Namespace` + +Specifies the namespace that the service resolver applies to. Refer to [namespaces](/consul/docs/enterprise/namespaces) for more information. + +#### Values + +- Default: None +- Data type: String + +### `Partition` + +Specifies the admin partition that the service resolver applies to. Refer to [admin partitions](/consul/docs/enterprise/admin-partitions) for more information. + +#### Values + +- Default: `default` +- Data type: String + +### `Meta` + +Specifies key-value pairs to add to the KV store. + +#### Values + +- Default: none +- Data type: Map of one or more key-value pairs + - ``: String + - ``: String or integer + +### `ConnectTimeout` + +Specifies the timeout duration for establishing new network connections to this service. By default, the duration is measured in nanoseconds (ns). + +#### Values + +- Default: None +- Data type: String + +### `RequestTimeout` + +Specifies the timeout duration for receiving an HTTP response from this service. When set to `0s`, the default value of `15s` is used instead. By default, the duration is measured in nanoseconds (ns). + +#### Values + +- Default: `15s` +- Data type: String + +### `Subsets` + +Specifies names for custom service subsets and the conditions under which service instances belong to each subset. Define a subset by specifying a key and a value where the key is the subset’s name and the value is a map that contains a [filtering expression](/consul/api-docs/features/filtering). If this parameter is not specified, only the unnamed default subset is usable. + +For additional guidance, refer to the [filter on service version configuration example](#filter-on-service-version). + +#### Values + +- Default: None +- Data type: Map containing a key-value pair. + - ``: String that names the subset. The string must be valid as a DNS subdomain element. + - ``: Map that can contain the following parameters: + + | Parameter | Description | Data type | Default | + | :------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ------- | + | `Filter` | Specifies an expression that filters the DNS elements of service instances that belong to the subset. If empty, all healthy instances of a service are returned. This expression can filter on the same DNS selectors as the [Health API endpoint](/consul/api-docs/health#filtering-2). For more information about creating and using expressions to filter, refer to [filtering](/consul/api-docs/features/filtering). | String | None | + | `OnlyPassing` | Determines if instances that return a warning from a health check are allowed to resolve a request. When set to `false`, instances with `passing` and `warning` states are considered healthy. When set to `true`, only instances with a `passing` health check state are considered healthy. | Boolean | `false` | + +### `DefaultSubset` + +Specifies a defined subset of service instances to use when no explicit subset is requested. If this parameter is not specified, Consul uses the unnamed default subset. + +#### Values + +- Default: None +- Data type: String + +### `Redirect` + +Specifies redirect instructions for local service traffic so that services deployed to a different network location resolve the upstream request instead. When this field is defined, Consul ignores all other fields in a service resolver configuration entry except for `Kind`, `Name`, `Namespace`. When there are multiple redirects defined for a single service, Consul uses only the first one it applies. + +#### Values + +- Default: None +- Data type: Map that can contain the following parameters: + - [`Service`](#redirect-service) + - [`ServiceSubset`](#redirect-servicesubset) + - [`Namespace`](#redirect-namespace) + - [`Partition`](#redirect-partition) + - [`Datacenter`](#redirect-datacenter) + - [`Peer`](#redirect-peer) + +### `Redirect{}.Service` + +Specifies the name of a service at the redirect’s destination that resolves local upstream requests. + +#### Values + +- Default: None +- Data type: String + +### `Redirect{}.ServiceSubset` + +Specifies the name of a subset of services at the redirect’s destination that resolves local upstream requests. If empty, the default subset is used. If specified, you must also specify at least one of the following in the same `Redirect` map: `Service`, `Namespace`, and`Datacenter`. + +#### Values + +- Default: None +- Data type: String + +### `Redirect{}.Namespace` + +Specifies the namespace at the redirect’s destination that resolves local upstream requests. + +#### Values + +- Default: None +- Data type: String + +### `Redirect{}.Partition` + +Specifies the admin partition at the redirect’s destination that resolves local upstream requests. + +#### Values + +- Default: None +- Data type: String + + +### `Redirect{}.Datacenter` + +Specifies the datacenter at the redirect’s destination that resolves local upstream requests. + +#### Values + +- Default: None +- Data type: String + +### `Redirect{}.Peer` + +Specifies the cluster with an active cluster peering connection at the redirect’s destination that resolves local upstream requests. Requires separately defined service intentions that [authorize services for peers](/consul/docs/connect/cluster-peering/usage/establish-cluster-peering#authorize-services-for-peers). When Consul runs a health check before resolving requests from the peer, it does not apply health checks that were defined on the peer and exported to the local cluster through the exported services configuration entry. + +#### Values + +- Default: None +- Data type: String + +### `Failover` + +Specifies controls for rerouting traffic to an alternate pool of service instances if the target service fails. + +This parameter is a map, and its key is the name of the local service subset that resolves to another location when it fails. You can specify a `"*"` wildcard to apply failovers to any subset. + +`Service`, `ServiceSubset`, `Namespace`, `Targets`, and `Datacenters` cannot all be empty at the same time. + +#### Values + +- Default: None +- Data type: Map that can contain the following parameters: + - [`Service`](#failover-service) + - [`ServiceSubset`](#failover-servicesubset) + - [`Namespace`](#failover-namespace) + - [`Datacenters`](#failover-datacenters) + - [`Targets`](#failover-targets) + +### `Failover{}.Service` + +Specifies the name of the service to resolve at the failover location during a failover scenario. + +#### Values + +- Default: None +- Data type: String + +### `Failover{}.ServiceSubset` + +Specifies the name of a subset of service instances to resolve at the failover location during a failover scenario. If empty, Consul uses the service’s [`DefaultSubset`](#defaultsubset). + +#### Values + +- Default: None +- Data type: String + +### `Failover{}.Namespace` + +Specifies the namespace at the failover location where the failover services are deployed. If empty, the current namespace is used. + +#### Values + +- Default: None +- Data type: String + +### `Failover{}.Datacenters` + +Specifies an ordered list of datacenters at the failover location to attempt connections to during a failover scenario. When Consul cannot establish a connection with the first datacenter in the list, it proceeds sequentially until establishing a connection with another datacenter. + +#### Values + +- Default: None +- Data type: String + +### `Failover{}.Targets` + +Specifies a fixed list of failover targets to try during failover. This list can express complicated failover scenarios. + +For examples, refer to the [failover example configurations](#service-failover). + +#### Values + +- Default: None +- Data type: List of maps that can contain the following parameters: + - [`Service`](#failover-targets-service) + - [`ServiceSubset`](#failover-targets-servicesubset) + - [`Namespace`](#failover-targets-namespace) + - [`Partition`](#failover-targets-partition) + - [`Datacenter`](#failover-targets-datacenter) + - [`Peer`](#failover-targets-peer) + +### `Failover{}.Targets[].Service` + +Specifies the service name to use for the failover target. If empty, the current service name is used. + +#### Values + +- Default: None +- Data type: String + +### `Failover{}.Targets[].ServiceSubset` + +Specifies the named subset to use for the failover target. If empty, the default subset for the requested service name is used. + +#### Values + +- Default: None +- Data type: String + +### `Failover{}.Targets[].Namespace` + +Specifies the namespace to use for the failover target. If empty, the default namespace is used. + +#### Values + +- Default: None +- Data type: String + +### `Failover{}.Targets[].Partition` + +Specifies the admin partition within the same datacenter to use for the failover target. If empty, the `default` partition is used. To use an admin partition in a different datacenter for the failover target, use the `Peer` field instead. + +#### Values + +- Default: None +- Data type: String + +### `Failover{}.Targets[].Datacenter` + +Specifies the WAN federated datacenter to use for the failover target. If empty, the current datacenter is used. To use a datacenter for the failover target that is connected with a cluster peering relationship rather than WAN federation, use the `Peer` field instead. + +#### Values + +- Default: None +- Data type: String + +### `Failover{}.Targets[].Peer` + +Specifies the destination cluster peer to resolve the target service name from. [Intentions](/consul/docs/connect/cluster-peering/create-manage-peering#authorize-services-for-peers) must be defined on the peered cluster so that the source service can access this failover target service as an upstream. When the peer name is specified, Consul uses Envoy's outlier detection to determine the health of the failover target based on whether services can communicate with the failover target. Consul ignores service health checks imported from a peer for failover targets because the checks do not account for service routers, splitters, and resolvers that may be defined in the peer for the target service. + +#### Values + +- Default: None +- Data type: String + +### `LoadBalancer` + +Specifies the load balancing policy and configuration for services issuing requests to this upstream. + +#### Values + +- Default: None +- Data type: Map that can contain the following parameters: + - [`Policy`](#loadbalancer-policy) + - [`RingHashConfig`](#loadbalancer-ringhashconfig) + - [`LeastRequestConfig`](#loadbalancer-leastrequestconfig) + - [`HashPolicies`](#loadbalancer-hashpolicies) + +### `LoadBalancer{}.Policy` + +Specifies the type of load balancing policy for selecting a host. Supported load balancing policies include: + +| Policy | Description | +| :----- | :-------------------------------------------------------------- | +| Random | The load balancer forwards a client request to an available server chosen at random from a fixed list. | +| Round robin | The load balancer proceeds through a fixed list of servers and forwards a client request to each available server in order. | +| Least request | The load balancer forwards a client request to the server with the fewest connections. When using this policy, you can specify additional parameters in [`LoadBalancer{}.LeastRequestConfig`](#loadbalancer-leastrequestconfig). | +| Ring hash | The load balancer forwards requests from the same client to the same group of servers. When using this policy, you can specify additional parameters in [`LoadBalancer{}.RingHashConfig`](#loadbalancer-ringhashconfig). | +| Maglev | The load balancer uses a hashing algorithm to spread requests evenly across servers. When using this policy, you can specify additional parameters in [`LoadBalancer{}.HashPolicies`](#loadbalancer-hashpolicies). | + + +#### Values + +- Default: None +- Data type: String containing one of the following values: + + - `random` + - `round_robin` + - `least_request` + - `ring_hash` + - `maglev` + +### `LoadBalancer{}.LeastRequestConfig` + +Specifies configuration for the `least_request` policy type. + +#### Values + +- Default: None +- Data type: Map containing the following parameter: + + | Parameter | Description | Data type | Default | + | :------------ | :------------------------------------------------------------------------------------------------- | --------- | ------- | + | `ChoiceCount` | Specifies the number of random healthy hosts from which to select the one with the least requests. | Integer | `2` | + +### `LoadBalancer{}.RingHashConfig` + +Specifies configuration for the `ring_hash` policy type. + +#### Values + +- Default: None +- Data type: List that can contain the following parameters: + + | Parameter | Description | Data type | Default | + | :------------ | :------------------------------------------------------------- | --------- | ------- | + | `MinimumRingSize` | Determines the minimum number of entries in the hash ring. | Integer | `1024` | + | `MaximumRingSize` | Determines the maximum number of entries in the hash ring. | Integer | `8192` | + +### `LoadBalancer{}.HashPolicies` + +Specifies a list of hash policies to use for hashing load balancing algorithms. Consul evaluates hash policies individually and combines them so that identical lists result in the same hash. If no hash policies are present or successfully evaluated, then Consul selects a random backend host. + +#### Values + +- Default: None +- Data type: List of maps for the following parameters: + - [`Field`](#loadbalancer-hashpolicies-field) + - [`FieldValue`](#loadbalancer-hashpolicies-fieldvalue) + - [`CookieConfig`](#loadbalancer-hashpolicies-cookieconfig) + - [`SourceIP`](#loadbalancer-hashpolicies-sourceip) + - [`Terminal`](#loadbalancer-hashpolicies-terminal) + +### `LoadBalancer{}.HashPolicies[].Field` + + Specifies the attribute type to hash on. You cannot specify the `Field` parameter if `SourceIP` is also configured. + + Supported attribute types include the following: + +| Attribute | Description | +| :--------- | :-------------------------------------------------------------- | +| Cookie | The load balancer uses a cookie to obtain a hash key. Refer to the [Envoy documentation](https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/route/v3/route_components.proto#envoy-v3-api-msg-config-route-v3-routeaction-hashpolicy-cookie) for more information. | +| Header | The load balancer uses a request header to obtain a hash key. Refer to the [Envoy documentation](https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/route/v3/route_components.proto#envoy-v3-api-msg-config-route-v3-routeaction-hashpolicy-header) for more information. | +| Query Parameter | The load balancer uses a URL query parameter to obtain the hash key. Refer to the [Envoy documentation](https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/route/v3/route_components.proto#envoy-v3-api-msg-config-route-v3-routeaction-hashpolicy-queryparameter) for more information. | + +#### Values + +- Default: None +- Data type: String containing one of the following values: + - `cookie` + - `header` + - `query_parameter` + +### `LoadBalancer{}.HashPolicies[].FieldValue` + +Specifies the value to hash, such as a header name, cookie name, or a URL query parameter name. You cannot specify the `FieldValue` parameter if `SourceIP` is also configured. + +#### Values + +- Default: None +- Data type: String + +### `LoadBalancer{}.HashPolicies[].CookieConfig` + +Specifies additional configuration options for the `cookie` hash policy type. This field causes Envoy to generate a cookie for a client on its first request. + +#### Values + +- Default: None +- Data type: Map that can contain the following parameters: + + | Parameter | Description | Data type | Default | + | :------------- | :-------------------------------------------------------------------------------- | --------- | ------- | + | `Session` | Directs Consul to generate a session cookie with no expiration. | Boolean | `false` | + | `TTL` | Specifies the TTL for generated cookies. Cannot be specified for session cookies. | String | `0s` | + | `Path` | Specifies the path to set for the cookie. | String | None | + +### `LoadBalancer{}.HashPolicies[].SourceIP` + +Determines if the hash type should besource IP address. You cannot specify `SourceIP` if `Field` or `FieldValue` are configured. + +#### Values + +- Default: `false` +- Data type: Boolean + +### `LoadBalancer{}.HashPolicies[].Terminal` + + Determines if Consul should stop computing the hash when multiple hash policies are present. If a hash is computed when a terminal policy is evaluated, then that hash is used and subsequent hash policies are ignored. + +#### Values -The `service-resolver` config entry kind (`ServiceResolver` on Kubernetes) controls which service instances -should satisfy service mesh upstream discovery requests for a given service name. +- Default: `false` +- Data type: Boolean + + -If no resolver config is defined the chain assumes 100% of traffic goes to the -healthy instances of the default service in the current datacenter+namespace -and discovery terminates. + -## Interaction with other Config Entries +### `apiVersion` -- Service resolver config entries are a component of [L7 Traffic - Management](/consul/docs/connect/l7-traffic). +Specifies the version of the Consul API for integrating with Kubernetes. The value must be `consul.hashicorp.com/v1alpha1`. -## UI +#### Values -Once a `service-resolver` is successfully entered, you can view it in the UI. Service routers, service splitters, and service resolvers can all be viewed by clicking on your service then switching to the *routing* tab. +- Default: None +- This field is required. +- String value that must be set to `consul.hashicorp.com/v1alpha1`. -![screenshot of service resolver in the UI](/img/l7-routing/Resolver.png) +### `kind` -## Sample Config Entries +Specifies the type of configuration entry to implement. Must be set to `ServiceResolver`. + +#### Values + +- Default: None +- This field is required. +- Data type: String value that must be set to `ServiceResolver`. + +## `metadata` + +Map that contains an arbitrary name for the configuration entry and the namespace it applies to. + +#### Values + +- Default: None +- Data type: Map + +### `metadata.name` + +Specifies a name for the configuration entry. The name is metadata that you can use to reference the configuration entry when performing Consul operations, such as applying a configuration entry to a specific cluster. + +#### Values + +- Default: None +- This field is required. +- Data type: String + +### `metadata.namespace` + +Specifies the namespace that the service resolver applies to. Refer to [namespaces](/consul/docs/enterprise/namespaces) for more information. + +#### Values + +- Default: None +- Data type: String + +### `spec` + +Map that contains the details about the `ServiceResolver` configuration entry. The `apiVersion`, `kind`, and `metadata` fields are siblings of the spec field. All other configurations are children. + +#### Values + +- Default: None +- This field is required. +- Data type: Map + +### `spec.connectTimeout` + +Specifies the timeout duration for establishing new network connections to this service. By default, the duration is measured in nanoseconds (ns). + +#### Values + +- Default: None +- Data type: String + +### `spec.requestTimeout` + +Specifies the timeout duration for receiving an HTTP response from this service. When set to `0s`, the default value of `15s` is used instead. By default, the duration is measured in nanoseconds (ns). + +#### Values + +- Default: `15s` +- Data type: String + +### `spec.subsets` + +Specifies names for custom service subsets and the conditions under which service instances belong to each subset. Define a subset by specifying a key and a value where the key is the subset’s name and the value is a map that contains a [filtering expression](/consul/api-docs/features/filtering). If this parameter is not specified, only the unnamed default subset is usable. + +For additional guidance, refer to the [filter on service version configuration example](#filter-on-service-version). + +#### Values + +- Default: None +- Data type: Map containing a key-value pair. + - ``: String that names the subset. The string must be valid as a DNS subdomain element. + - ``: Map that can contain the following parameters: + + | Parameter | Description | Data type | Default | + | :------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ------- | + | `filter` | Specifies an expression that filters the DNS elements of service instances that belong to the subset. If empty, all healthy instances of a service are returned. This expression can filter on the same DNS selectors as the [Health API endpoint](/consul/api-docs/health#filtering-2). For more information about creating and using expressions to filter, refer to [filtering](/consul/api-docs/features/filtering). | String | None | + | `onlyPassing` | Determines if instances that return a warning from a health check are allowed to resolve a request. When set to `false`, instances with `passing` and `warning` states are considered healthy. When set to `true`, only instances with a `passing` health check state are considered healthy. | Boolean | `false` | + +### `spec.defaultSubset` + +Specifies a defined subset of service instances to use when no explicit subset is requested. If this parameter is not specified, Consul uses the unnamed default subset. + +#### Values + +- Default: None +- Data type: String + +### `spec.redirect` + +Specifies redirect instructions for local service traffic so that services deployed to a different network location resolve the upstream request instead. When this field is defined, Consul ignores all other fields in a service resolver configuration entry except for `kind`, `name`, `namespace`. When there are multiple redirects defined for a single service, Consul uses only the first one it applies. + +#### Values + +- Default: None +- Data type: Map that can contain the following parameters: + - [`service`](#spec-redirect-service) + - [`serviceSubset`](#spec-redirect-servicesubset) + - [`namespace`](#spec-redirect-namespace) + - [`partition`](#spec-redirect-partition) + - [`datacenter`](#spec-redirect-datacenter) + - [`peer`](#spec-redirect-peer) + +### `spec.redirect.service` + +Specifies the name of a service at the redirect’s destination that resolves local upstream requests. + +#### Values + +- Default: None +- Data type: String + +### `spec.redirect.serviceSubset` + +Specifies the name of a subset of services at the redirect’s destination that resolves local upstream requests. If empty, the default subset is used. If specified, you must also specify at least one of the following in the same `redirect` map: `service`, `namespace`, and`datacenter`. + +#### Values + +- Default: None +- Data type: String + +### `spec.redirect.namespace` + +Specifies the namespace at the redirect’s destination that resolves local upstream requests. + +#### Values + +- Default: None +- Data type: String + +### `spec.redirect.partition` + +Specifies the admin partition at the redirect’s destination that resolves local upstream requests. + +#### Values + +- Default: None +- Data type: String + + +### `spec.redirect.datacenter` + +Specifies the datacenter at the redirect’s destination that resolves local upstream requests. + +#### Values + +- Default: None +- Data type: String + +### `spec.redirect.peer` + +Specifies the cluster with an active cluster peering connection at the redirect’s destination that resolves local upstream requests. Requires separately defined service intentions that [authorize services for peers](/consul/docs/connect/cluster-peering/usage/establish-cluster-peering#authorize-services-for-peers). When Consul runs a health check before resolving requests from the peer, it does not apply health checks that were defined on the peer and exported to the local cluster through the exported services configuration entry. + +#### Values + +- Default: None +- Data type: String + +### `spec.failover` + +Specifies controls for rerouting traffic to an alternate pool of service instances if the target service fails. + +This parameter is a map, and its key is the name of the local service subset that resolves to another location when it fails. You can specify a `"*"` wildcard to apply failovers to any subset. + +`service`, `serviceSubset`, `namespace`, `targets`, and `datacenters` cannot all be empty at the same time. + +#### Values + +- Default: None +- Data type: Map that can contain the following parameters: + - [`service`](#spec-failover-service) + - [`serviceSubset`](#spec-failover-servicesubset) + - [`namespace`](#spec-failover-namespace) + - [`datacenters`](#spec-failover-datacenters) + - [`targets`](#spec-failover-targets) + +### `spec.failover.service` + +Specifies the name of the service to resolve at the failover location during a failover scenario. + +#### Values + +- Default: None +- Data type: String + +### `spec.failover.serviceSubset` + +Specifies the name of a subset of service instances to resolve at the failover location during a failover scenario. If empty, Consul uses the service’s [`defaultSubset`](#defaultsubset). + +#### Values + +- Default: None +- Data type: String + +### `spec.failover.namespace` + +Specifies the namespace at the failover location where the failover services are deployed. If empty, the current namespace is used. + +#### Values + +- Default: None +- Data type: String + +### `spec.failover.datacenters` + +Specifies an ordered list of datacenters at the failover location to attempt connections to during a failover scenario. When Consul cannot establish a connection with the first datacenter in the list, it proceeds sequentially until establishing a connection with another datacenter. + +#### Values + +- Default: None +- Data type: String + +### `spec.failover.targets` + +Specifies a fixed list of failover targets to try during failover. This list can express complicated failover scenarios. + +For examples, refer to the [failover example configurations](#service-failover). + +#### Values + +- Default: None +- Data type: List of maps that can contain the following parameters: + - [`service`](#spec-failover-targets-service) + - [`serviceSubset`](#spec-failover-targets-servicesubset) + - [`namespace`](#spec-failover-targets-namespace) + - [`partition`](#spec-failover-targets-partition) + - [`datacenter`](#spec-failover-targets-datacenter) + - [`peer](#spec-failover-targets-peer) + +### `spec.failover.targets.service` + +Specifies the service name to use for the failover target. If empty, the current service name is used. + +#### Values + +- Default: None +- Data type: String + +### `spec.failover.targets.serviceSubset` + +Specifies the named subset to use for the failover target. If empty, the default subset for the requested service name is used. + +#### Values + +- Default: None +- Data type: String + +### `spec.failover.targets.namespace` + +Specifies the namespace to use for the failover target. If empty, the default namespace is used. + +#### Values + +- Default: None +- Data type: String + +### `spec.failover.targets.partition` + +Specifies the admin partition within the same datacenter to use for the failover target. If empty, the `default` partition is used. To use an admin partition in a different datacenter for the failover target, use the `peer` field instead. + +#### Values + +- Default: None +- Data type: String + +### `spec.failover.targets.datacenter` + +Specifies the WAN federated datacenter to use for the failover target. If empty, the current datacenter is used. To use a datacenter for the failover target that is connected with a cluster peering relationship rather than WAN federation, use the `peer` field instead. + +#### Values + +- Default: None +- Data type: String + +### `spec.failover.targets.peer` + +Specifies the destination cluster peer to resolve the target service name from. [Intentions](/consul/docs/k8s/connect/cluster-peering/usage/establish-peering#authorize-services-for-peers) must be defined on the peered cluster so that the source service can access this failover target service as an upstream. When the peer name is specified, Consul uses Envoy's outlier detection to determine the health of the failover target based on whether services can communicate with the failover target. Consul ignores service health checks imported from a peer for failover targets because the checks do not account for service routers, splitters, and resolvers that may be defined in the peer for the target service. + +#### Values + +- Default: None +- Data type: String + +### `spec.loadBalancer` + +Specifies the load balancing policy and configuration for services issuing requests to this upstream. + +#### Values + +- Default: None +- Data type: Map that can contain the following parameters: + - [`policy`](#spec-loadbalancer-policy) + - [`leastRequestConfig`](#spec-loadbalancer-leastrequestconfig) + - [`ringHashConfig`](#spec-loadbalancer-ringhashconfig) + - [`hashPolicies`](#spec-loadbalancer-hashpolicies) + +### `spec.loadBalancer.policy` + +Specifies the type of load balancing policy for selecting a host. Supported load balancing policies include: + +| Policy | Description | +| :----- | :-------------------------------------------------------------- | +| Random | The load balancer forwards a client request to an available server chosen at random from a fixed list. | +| Round robin | The load balancer proceeds through a fixed list of servers and forwards a client request to each available server in order. | +| Least request | The load balancer forwards a client request to the server with the fewest connections. When using this policy, you can specify additional parameters in [`spec.loadBalancer.leastRequestConfig`](#spec-loadbalancer-leastrequestconfig). | +| Ring hash | The load balancer forwards requests from the same client to the same group of servers. When using this policy, you can specify additional parameters in [`spec.loadBalancer.ringHashConfig`](#spec-loadbalancer-ringhashconfig). | +| Maglev | The load balancer uses a hashing algorithm to spread requests evenly across servers. When using this policy, you can specify additional parameters in [`spec.loadBalancer.hashPolicies`](#spec-loadbalancer-hashpolicies). | + +#### Values + +- Default: None +- Data type: String containing one of the following values: + + - `random` + - `round_robin` + - `least_request` + - `ring_hash` + - `maglev` + +### `spec.loadBalancer.leastRequestConfig` + +Specifies configuration for the `least_request` policy type. + +#### Values + +- Default: None +- Data type: Map containing the following parameter: + + | Parameter | Description | Data type | Default | + | :------------ | :------------------------------------------------------------------------------------------------- | --------- | ------- | + | `choiceCount` | Specifies the number of random healthy hosts from which to select the one with the least requests. | Integer | `2` | + +### `spec.loadBalancer.ringHashConfig` + +Specifies configuration for the `ring_hash` policy type. + +#### Values + +- Default: None +- Data type: List that can contain the following parameters: + + | Parameter | Description | Data type | Default | + | :------------ | :------------------------------------------------------------- | --------- | ------- | + | `minimumRingSize` | Determines the minimum number of entries in the hash ring. | Integer | `1024` | + | `maximumRingSize` | Determines the maximum number of entries in the hash ring. | Integer | `8192` | + +### `spec.loadBalancer.hashPolicies` + +Specifies a list of hash policies to use for hashing load balancing algorithms. Consul evaluates hash policies individually and combines them so that identical lists result in the same hash. If no hash policies are present or successfully evaluated, then Consul selects a random backend host. + +#### Values + +- Default: None +- Data type: List that can contain the following parameters: + - [`field`](#spec-loadbalancer-hashpolicies-field) + - [`fieldValue`](#spec-loadbalancer-hashpolicies-fieldvalue) + - [`cookieConfig`](#spec-loadbalancer-hashpolicies-cookieconfig) + - [`sourceIP`](#spec-loadbalancer-hashpolicies-sourceip) + - [`terminal`](#spec-loadbalancer-hashpolicies-terminal) + +### `spec.loadBalancer.hashPolicies[].field` + + Specifies the attribute type to hash on. You cannot specify the `field` parameter if `sourceIP` is also configured. + +Supported attribute types include the following: + +| Attribute | Description | +| :--------- | :-------------------------------------------------------------- | +| Cookie | The load balancer uses a cookie to obtain a hash key. Refer to the [Envoy documentation](https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/route/v3/route_components.proto#envoy-v3-api-msg-config-route-v3-routeaction-hashpolicy-cookie) for more information. | +| Header | The load balancer uses a request header to obtain a hash key. Refer to the [Envoy documentation](https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/route/v3/route_components.proto#envoy-v3-api-msg-config-route-v3-routeaction-hashpolicy-header) for more information. | +| Query Parameter | The load balancer uses a URL query parameter to obtain the hash key. Refer to the [Envoy documentation](https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/route/v3/route_components.proto#envoy-v3-api-msg-config-route-v3-routeaction-hashpolicy-queryparameter) for more information. | + +#### Values + +- Default: None +- Data type: String containing one of the following values: + - `cookie` + - `header` + - `query_parameter` + +### `spec.loadBalancer.hashPolicies[].fieldValue` + +Specifies the value to hash, such as a header name, cookie name, or a URL query parameter name. You cannot specify the `fieldValue` parameter if `sourceIP` is also configured. + +#### Values + +- Default: None +- Data type: String + +### `spec.loadBalancer.hashPolicies[].cookieConfig` + +Specifies additional configuration options for the `cookie` hash policy type. This field causes Envoy to generate a cookie for a client on its first request. + +#### Values + +- Default: None +- Data type: Map that can contain the following parameters: + + | Parameter | Description | Data type | Default | + | :------------- | :-------------------------------------------------------------------------------- | --------- | ------- | + | `session` | Directs Consul to generate a session cookie with no expiration. | Boolean | `false` | + | `ttl` | Specifies the TTL for generated cookies. Cannot be specified for session cookies. | String | `0s` | + | `path` | Specifies the path to set for the cookie. | String | None | + +### `spec.loadBalancer.hashPolicies[].sourceIP` + +Determines if the hash type should besource IP address. You cannot specify `sourceIP` if `field` or `fieldValue` are configured. + +#### Values + +- Default: `false` +- Data type: Boolean + +### `spec.loadBalancer.hashPolicies[].terminal` + +Determines if Consul should stop computing the hash when multiple hash policies are present. If a hash is computed when a terminal policy is evaluated, then that hash is used and subsequent hash policies are ignored. + +#### Values + +- Default: `false` +- Data type: Boolean + + + + +## Examples + +The following examples demonstrate common service resolver configuration patterns for specific use cases. ### Filter on service version -Create service subsets based on a version metadata and override the defaults: +The following example creates two subsets of the `web` service and assigns service instances to subsets based on each instance's version metadata. It also defines `v1` as the default subset. - + + ```hcl Kind = "service-resolver" @@ -50,6 +1257,10 @@ Subsets = { } ``` + + + + ```yaml apiVersion: consul.hashicorp.com/v1alpha1 kind: ServiceResolver @@ -64,6 +1275,10 @@ spec: filter: 'Service.Meta.version == v2' ``` + + + + ```json { "Kind": "service-resolver", @@ -80,13 +1295,15 @@ spec: } ``` - + + -### Other datacenters +### Resolve virtual upstreams -Expose a set of services in another datacenter as a virtual service: +The folowing example uses the [`Redirect` parameter](#redirect) to expose a set of services to another datacenter as a virtual service. - + + ```hcl Kind = "service-resolver" @@ -97,6 +1314,10 @@ Redirect { } ``` + + + + ```yaml apiVersion: consul.hashicorp.com/v1alpha1 kind: ServiceResolver @@ -108,6 +1329,10 @@ spec: datacenter: dc2 ``` + + + + ```json { "Kind": "service-resolver", @@ -119,13 +1344,15 @@ spec: } ``` - + + -### Failover +### Service failover -Enable failover for subset `v2` to `dc2`, and all other subsets to `dc3` or `dc4`: +The following example enables failover for subset `v2` to `dc2`. All other subsets attempt failover to `dc3`, and when it is not available, to `dc4`: - + + ```hcl Kind = "service-resolver" @@ -141,6 +1368,10 @@ Failover = { } ``` + + + + ```yaml apiVersion: consul.hashicorp.com/v1alpha1 kind: ServiceResolver @@ -155,6 +1386,10 @@ spec: datacenters: ['dc3', 'dc4'] ``` + + + + ```json { "Kind": "service-resolver", @@ -171,12 +1406,15 @@ spec: } ``` - + + + +#### Failover targets for federation and cluster peering -Enable failover to a WAN federated datacenter and then a cluster peer for all -service subsets. +The following example enables failover to target a WAN federated datacenter for all service subsets. If the connection to `dc3` times out after 15 seconds, the service failover targets the peer with the establish cluster peering connection instead. - + + ```hcl Kind = "service-resolver" @@ -192,6 +1430,10 @@ Failover = { } ``` + + + + ```yaml apiVersion: consul.hashicorp.com/v1alpha1 kind: ServiceResolver @@ -206,6 +1448,10 @@ spec: - peer: "peer-01" ``` + + + + ```json { "Kind": "service-resolver", @@ -222,13 +1468,15 @@ spec: } ``` - + + + +#### Failover for all service subsets - - Failover to another datacenter and namespace for all service subsets. - +The following example enables failover to the `secondary` namespace in another datacenter for all service subsets. - + + ```hcl Kind = "service-resolver" @@ -243,6 +1491,10 @@ Failover = { } ``` + + + + ```yaml apiVersion: consul.hashicorp.com/v1alpha1 kind: ServiceResolver @@ -256,6 +1508,10 @@ spec: datacenters: ['dc2'] ``` + + + + ```json { "Kind": "service-resolver", @@ -271,13 +1527,15 @@ spec: } ``` - + + + +#### Failover to a namespace - - Failover within a datacenter and a different namespace. - +The following example enables failover to a different namespace in the same datacenter. - + + ```hcl Kind = "service-resolver" @@ -292,6 +1550,10 @@ Failover = { } ``` + + + + ```yaml apiVersion: consul.hashicorp.com/v1alpha1 kind: ServiceResolver @@ -305,6 +1567,10 @@ spec: namespace: 'secondary' ``` + + + + ```json { "Kind": "service-resolver", @@ -320,13 +1586,15 @@ spec: } ``` - + + ### Consistent load balancing -Apply consistent load balancing for requests based on `x-user-id` header: +The following example applies a Maglev load balancing policy for requests with an `x-user-id` header: - + + ```hcl Kind = "service-resolver" @@ -343,6 +1611,10 @@ LoadBalancer = { } ``` + + + + ```yaml apiVersion: consul.hashicorp.com/v1alpha1 kind: ServiceResolver @@ -356,6 +1628,10 @@ spec: fieldValue: x-user-id ``` + + + + ```json { "Kind": "service-resolver", @@ -372,6 +1648,7 @@ spec: } ``` +<<<<<<< HEAD ## Available Fields @@ -806,3 +2083,7 @@ name in these fields: - [`Redirect.Service`](#service) - [`Failover[].Service`](#service-1) +======= + + +>>>>>>> bd5a3c137d (docs: Reference pages for service-router and service-resolver config entries (#17145)) diff --git a/website/content/docs/connect/config-entries/service-router.mdx b/website/content/docs/connect/config-entries/service-router.mdx index 64d0a11b53de..4362925f59fb 100644 --- a/website/content/docs/connect/config-entries/service-router.mdx +++ b/website/content/docs/connect/config-entries/service-router.mdx @@ -1,55 +1,1314 @@ --- layout: docs -page_title: Service Router - Configuration Entry Reference -description: >- - The service router configuration entry kind defines where the service mesh routes requests based on L7 network information such as header or path. Use the reference guide to learn about `""service-router""` config entry parameters and how behaviors like request timeouts, retry behavior, header modification, and path rewriting can be applied to a request based on its header or path information. +page_title: Service Router Configuration Entry Reference +description: >- + Service router configuration entries are L7 traffic management tools for redirecting requests for a service to a particular instance or set of instances. Learn how to write `service-router` config entries in HCL or YAML with a specification reference, configuration model, a complete example, and example code by use case. --- -# Service Router Configuration Entry +# Service router configuration entry reference + +This page provides reference information for service router configuration entries. Service routers use L7 network information to redirect a traffic request for a service to one or more specific service instances. + +Refer to [L7 traffic management overview](/consul/docs/connect/l7-traffic) for additional information. + +## Configuration model + +The following list outlines field hierarchy, language-specific data types, and requirements in this configuration entry. Click on a property name to view additional details, including default values. + + + + + +- [`Kind`](#kind): string | required | must be set to `service-router` +- [`Name`](#name): string | required +- [`Namespace`](#namespace): string +- [`Partition`](#partition): string | `default` +- [`Meta`](#meta): map +- [`Routes`](#routes): list + - [`Match`](#routes-match): map + - [`HTTP`](#routes-match-http): map + - [`PathExact`](#routes-match-http-pathexact): string + - [`PathPrefix`](#routes-match-http-pathprefix): string + - [`PathRegex`](#routes-match-http-pathregex): string + - [`Methods`](#routes-match-http-methods): list + - [`Header`](#routes-match-http-header): list + - [`Name`](#routes-match-http-header-name): string + - [`Present`](#routes-match-http-header-present): boolean | `false` + - [`Exact`](#routes-match-http-header-exact): string + - [`Prefix`](#routes-match-http-header-prefix): string + - [`Suffix`](#routes-match-http-header-suffix): string + - [`Regex`](#routes-match-http-header-regex): string + - [`Invert`](#routes-match-http-header-invert): boolean | `false` + - [`QueryParam`](#routes-match-http-queryparam): list + - [`Name`](#routes-match-http-queryparam-name): string + - [`Present`](#routes-match-http-queryparam-present): boolean | `false` + - [`Exact`](#routes-match-http-queryparam-exact): string + - [`Regex`](#routes-match-http-queryparam-regex): string + - [`Destination`](#routes-destination): map + - [`Service`](#routes-destination-service): string + - [`ServiceSubset`](#routes-destination-servicesubset): string + - [`Namespace`](#routes-destination-namespace): string + - [`Partition`](#routes-destination-partition): string + - [`PrefixRewrite`](#routes-destination-prefixrewrite): string + - [`RequestTimeout`](#routes-destination-requesttimeout): integer | `0` + - [`IdleTimeout`](#routes-destination-idletimeout): integer | `0` + - [`NumRetries`](#routes-destination-numretries): integer | `1` + - [`RetryOnConnectFailure`](#routes-destination-retryonconnectfailure): boolean | `false` + - [`RetryOn`](#routes-destination-retryon): list + - [`RetryOnStatusCodes`](#routes-destination-retryonstatuscodes): list + - [`RequestHeaders`](#routes-destination-requestheaders): map + - [`Add`](#routes-destination-requestheaders): map + - [`Set`](#routes-destination-requestheaders): map + - [`Remove`](#routes-destination-requestheaders): map + - [`ResponseHeaders`](#routes-destination-responseheaders): map + - [`Add`](#routes-destination-responseheaders): map + - [`Set`](#routes-destination-responseheaders): map + - [`Remove`](#routes-destination-responseheaders): map + + + + + +- [`apiVersion`](#apiversion): string | required | must be set to `consul.hashicorp.com/v1alpha1` +- [`kind`](#kind): string | required | must be set to `ServiceRouter` +- [`metadata`](#metadata): map | required + - [`name`](#metadata-name): string | required + - [`namespace`](#metadata-namespace): string | optional +- [`spec`](#spec): map | required + - [`routes`](#spec-routes): list + - [`match`](#spec-routes-match): map + - [`http`](#spec-routes-match-http): map + - [`pathExact`](#spec-routes-match-http-pathexact): string + - [`pathPrefix`](#spec-routes-match-http-pathprefix): string + - [`pathRegex`](#spec-routes-match-http-pathregex): string + - [`methods`](#spec-routes-match-http-methods): list + - [`header`](#spec-routes-match-http-header): list + - [`name`](#spec-routes-match-http-header-name): string + - [`present`](#spec-routes-match-http-header-present): boolean | `false` + - [`exact`](#spec-routes-match-http-header-exact): string + - [`prefix`](#spec-routes-match-http-header-prefix): string + - [`suffix`](#spec-routes-match-http-header-suffix): string + - [`regex`](#spec-routes-match-http-header-regex): string + - [`invert`](#spec-routes-match-http-header-invert): boolean + - [`queryParam`](#spec-routes-match-http-queryparam): list + - [`name`](#spec-routes-match-http-queryparam-name): string + - [`present`](#spec-routes-match-http-queryparam-present): boolean | `false` + - [`regex`](#spec-routes-match-http-queryparam-regex): string + - [`destination`](#spec-routes-destination): map + - [`service`](#spec-routes-destination-service): string + - [`serviceSubset`](#spec-routes-destination-servicesubset): string + - [`namespace`](#spec-routes-destination-namespace): string + - [`partition`](#spec-routes-destination-partition): string + - [`prefixRewrite`](#spec-routes-destination-prefixrewrite): string + - [`requestTimeout`](#spec-routes-destination-requesttimeout): integer | `0` + - [`numRetries`](#spec-routes-destination-numretries): integer | `0` + - [`numRetries`](#spec-routes-destination-numretries): integer | `1` + - [`retryOnConnectFailure`](#spec-routes-destination-retryonconnectfailure): boolean | `false` + - [`retryOn`](#spec-routes-destination-retryon): list + - [`retryOnStatusCodes`](#spec-routes-destination-retryonstatuscodes): list + - [`requestHeaders`](#spec-routes-destination-requestheaders): map + - [`add`](#spec-routes-destination-requestheaders): map + - [`set`](#spec-routes-destination-requestheaders): map + - [`remove`](#spec-routes-destination-requestheaders): map + - [`responseHeaders`](#spec-routes-destination-responseheaders): map + - [`add`](#spec-routes-destination-responseheaders): map + - [`set`](#spec-routes-destination-responseheaders): map + - [`remove`](#spec-routes-destination-responseheaders): map + + + + +## Complete configuration + +When every field is defined, a service router configuration entry has the following form: + + + + -The `service-router` config entry kind (`ServiceRouter` on Kubernetes) controls service mesh traffic routing and -manipulation at networking layer 7 (e.g. HTTP). +```hcl +Kind = "service-router" ## required +Name = "" ## required +Namespace = "" +Partition = "" +Meta = { + = "" +} + + +Routes = [ + { + Match { + HTTP { + PathExact = "" ## cannot specify with PathPrefix or PathRegex + }, + HTTP { + PathPrefix = "" ## cannot specify with PathExact or PathRegex + }, + HTTP { + PathRegex = "" ## cannot specify with PathPrefix or PathExact + }, + HTTP { + Methods = ["GET", "POST", "PUT"] + }, + HTTP { + Header = [ ## do not specify Present, Exact, Prefix, Suffix, and Regex in a single Header + { + Name = "" ## required when specifying Routes.Match.HTTP.Header + Present = false + Exact = "" + Prefix = "" + Suffix = "" + Regex = "" + Invert = false + } + ] + } + HTTP { + QueryParam = [ ## do not specify Present, Exact, and Regex in a single QueryParam + Name = "" ## required when specifying Routes.Match.HTTP.Header + Present = false + Exact = "" + Regex = "" + ] + } + }, + + + Destination { + Service = "" + ServiceSubset = "" + Namespace = "" + Partition = "" + PrefixRewrite = "" ## required specifying either Routes.Match.HTTP.PathPrefix or Routes.Match.HTTP.PathExact + RequestTimeout = 0 + IdleTimeout = 0 + NumRetries = 1 + RetryOnConnectFailure = false + RetryOn = ["reset", "unavailable"] + RetryOnStatusCodes = [500, 502, 503] + RequestHeaders = { + Set = { + "X-Web-Version" : "" + } + } + ResponseHeaders = { + Set = { + "X-Web-Version" : "" + } + } + } + } +] +``` + + + + + +```json +{ + "Kind": "service-router", // required + "Name": "", // required + "Namespace": "", + "Partition": "", + "Meta": { + "": "" + }, + + "Routes": [ + { + "Match": { + "HTTP": { + "PathExact": "" // cannot specify with PathPrefix or PathRegex + }, + "HTTP": { + "PathPrefix": "" // cannot specify with PathExact or PathRegex + }, + "HTTP": { + "PathRegex": "" // cannot specify with PathPrefix or PathExact + }, + "HTTP": { + "Methods": ["GET", "POST", "PUT"] + }, + "HTTP": { + "Header": [ // do not specify Present, Exact, Prefix, Suffix, and Regex in a single Header + { + "Name": "", // required when specifying Routes.Match.HTTP.Header + "Present": false, + "Exact": "", + "Prefix": "", + "Suffix": "", + "Regex": "", + "Invert": false, + } + ] + }, + "HTTP": { + "QueryParam": [ // do not specify Present, Exact, and Regex in a single QueryParam + "Name": "", // required when specifying Routes.Match.HTTP.Header + "Present": false, + "Exact": "", + "Regex": "" + ] + } + }, + + "Destination": { + "Service": "", + "ServiceSubset": "", + "Namespace": "", + "Partition": "", + "PrefixRewrite": "", // required specifying either Routes.Match.HTTP.PathPrefix or Routes.Match.HTTP.PathExact + "RequestTimeout": 0, + "IdleTimeout": 0, + "NumRetries": 1, + "RetryOnConnectFailure": false, + "RetryOn": ["reset", "unavailable"], + "RetryOnStatusCodes": [500, 502, 503], + "RequestHeaders": { + "Set": { + "X-Web-Version" : "" + } + }, + "ResponseHeaders": { + "Set": { + "X-Web-Version" : "" + } + } + } + } + ] +} +``` + + + + + +```yaml +apiVersion: consul.hashicorp.com/v1alpha1 # required +kind: ServiceRouter # required +metadata: + name: + namespace: +spec: + routes: + - match: + http: + pathExact: ## cannot specify with pathPrefix or pathRegex + http: + pathPrefix: ## cannot specify with pathExact or pathRegex + http: + pathRegex: ## cannot specify with pathPrefix or pathExact + http: + methods: [GET, POST, PUT] + http: + header: ## do not specify present, exact, prefix, suffix, and regex in a single header + - name: ## required when specifying spec.routes.match.http.header + present: false + exact: + prefix: + suffix: + regex: + invert: false + http: + queryParam: ## do not specify present, exact, and regex in a single queryParam + - name: ## required when specifying spec.routes.match.http.header + present: false + exact: + regex: + + destination: + service: + serviceSubset: + namespace: + partition: + prefixRewrite: ## required specifying either spec.routes.match.http.pathPrefix or spec.routes.match.http.pathExact + requestTimeout: 0 + idleTimeout: 0 + numRetries: 1 + retryOnConnectFailure: false + retryOn: ['reset'] + retryOnStatusCodes: [500, 502, 503] + requestHeaders: + set: + x-Web-Version: + responseHeaders: + set: + x-Web-Version: +``` + + + + + +## Specification + +This section provides details about the fields you can configure in the service router configuration entry. + + + + + +### `Kind` + +Specifies the type of configuration entry to implement. + +#### Values + +- Default: none +- This field is required. +- Data type: String value that must be set to `service-router`. + +### `Name` + +Specifies a name for the configuration entry. The name is metadata that you can use to reference the configuration entry when performing Consul operations with the [`consul config` command](/consul/commands/config). + +#### Values + +- Default: None +- Data type: String + +### `Namespace` + +Specifies the namespace to apply the configuration entry to. Refer to [Namespaces](/consul/docs/enterprise/namespaces) for additional information about Consul namespaces. + +#### Values + +- Default: None +- Data type: String + +### `Partition` + +Specifies the admin partition to apply the configuration entry to. Refer to [Admin partitions](/consul/docs/enterprise/admin-partitions) for additional information. + +#### Values + +- Default: `default` +- Data type: String + +### `Meta` + +Specifies key-value pairs to add to the KV store. + +#### Values + +- Default: None +- Data type: Map of one or more key-value pairs + - ``: String + - ``: String or integer + +### `Routes` + +Defines the possible routes for L7 requests. Consul evaluates traffic against the list of routes in their order of appearance in the configuration entry. When multiple routes satisfy the request, Consul uses the first route that matches. Traffic that fails to match any of the provided routes is routed to the default service. + +#### Values + +- Default: None +- Data type: List that can contain the following parameters: + +- [`Match`](#routes-match) +- [`Destination`](#routes-destination) + +### `Routes[].Match` + +Describes a set of criteria that Consul compares incoming L7 traffic with. If empty or omitted, it acts as a catch-all. + +#### Values + +- Default: None +- Data type: Map that contains the [`Routes[].Match{}.HTTP`](#routes-match-http) parameter. + +### `Routes[].Match{}.HTTP` + +Specifies a set of HTTP criteria used to evaluate incoming L7 traffic for matches. + +When matching on the HTTP request path, you can only match on one path at a time. Do not configure `PathExact`, `PathPrefix`, and `PathRegex` in a single HTTP map. + +#### Values + +- Default: None +- Data type: Map that can contain the following parameters: + + - [`PathExact`](#routes-match-http-pathexact) + - [`PathPrefix`](#routes-match-http-pathprefix) + - [`PathRegex`](#routes-match-http-pathregex) + - [`Methods`](#routes-match-http-methods) + - [`Header`](#routes-match-http-header) + - [`QueryParam`](#routes-match-http-queryparam) + +### `Routes[].Match{}.HTTP{}.PathExact` + +Specifies the exact path to match on the HTTP request path. When using this field, do not configure `PathPrefix` or `PathRegex` in the same HTTP map. + +#### Values + +- Default: None +- Data type: String + +### `Routes[].Match{}.HTTP{}.PathPrefix` + +Specifies the path prefix to match on the HTTP request path. When using this field, do not configure `PathExact` or `PathRegex` in the same HTTP map. + +#### Values + +- Default: None +- Data type: String + +### `Routes[].Match{}.HTTP{}.PathRegex` + +Specifies a regular expression to match on the HTTP request path. When using this field, do not configure `PathExact` or `PathPrefix` in the same HTTP map. The syntax for the regular expression field is proxy-specific. When [using Envoy](/consul/docs/connect/proxies/envoy), refer to [the documentation for Envoy v1.11.2 or newer](https://github.com/google/re2/wiki/Syntax) or [the documentation for Envoy v1.11.1 or older](https://en.cppreference.com/w/cpp/regex/ecmascript), depending on the version of Envoy you use. + +#### Values + +- Default: None +- Data type: String + +### `Routes[].Match{}.HTTP{}.Methods` + +Specifies HTTP methods that the match applies to. If not specified, the request matches on all HTTP methods. If provided, the name must be a valid method formatted as a string. + +String values must be a valid [HTTP request method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods). + +#### Values + +- Default: None +- Data type: List of strings. Each string must match one of the following values: + - `GET` + - `HEAD` + - `POST` + - `PUT` + - `DELETE` + - `CONNECT` + - `OPTIONS` + - `TRACE` + - `PATCH` + +### `Routes[].Match{}.HTTP{}.Header` + +Specifies information in the HTTP request header to match with. When more than one field is configured, all criteria must match for the service routing to apply. + +When using this field, do not configure `Present`, `Exact`, `Prefix`, `Suffix`, and `Regex` in the same HTTP map. You can use only one of these fields at a time when configuring match criteria for HTTP headers, as they are mutually exclusive with one another. + +#### Values + +- Default: None +- Data type: List containing one or more of the following parameters: + + - [`Name`](#routes-match-http-header-name) + - [`Present`](#routes-match-http-header-present) + - [`Exact`](#routes-match-http-header-exact) + - [`Prefix`](#routes-match-http-header-prefix) + - [`Suffix`](#routes-match-http-header-suffix) + - [`Regex`](#routes-match-http-header-regex) + - [`Invert`](#routes-match-http-header-invert) + +### `Routes[].Match{}.HTTP{}.Header[].Name` + +Specifies the name of the HTTP header to match. This field is required when using [`Routes[].Match{}.HTTP{}.Header`](#routes-match-http-header). + +#### Values + +- Default: None +- Data type: String + +### `Routes[].Match{}.HTTP{}.Header[].Present` + +Specifies that a request matches when the value in the `Name` field is present anywhere in the HTTP header. When using this field, do not configure `Exact`, `Prefix`, `Suffix`, or `Regex` in the same HTTP map. + +#### Values + +- Default: `false` +- Data type: Boolean + +### `Routes[].Match{}.HTTP{}.Header[].Exact` + +Specifies that a request matches when the header with the given name is this exact value. When using this field, do not configure `Present`, `Prefix`, `Suffix`, or `Regex` in the same HTTP map. + +#### Values + +- Default: None +- Data type: String + +### `Routes[].Match{}.HTTP{}.Header[].Prefix` + +Specifies that a request matches when the header with the given name has this prefix. When using this field, do not configure `Present`, `Exact`, `Suffix`, or `Regex` in the same HTTP map. + +#### Values + +- Default: None +- Data type: String + +### `Routes[].Match{}.HTTP{}.Header[].Suffix` + +Specifies that a request matches when the header with the given name has this suffix. When using this field, do not configure `Present`, `Exact`, `Prefix`, or `Regex` in the same HTTP map. + +#### Values + +- Default: None +- Data type: String + +### `Routes[].Match{}.HTTP{}.Header[].Regex` + +Specifies that a request matches when the header with the given name matches this regular expression. When using this field, do not configure `Present`, `Exact`, `Prefix`, or `Suffix` in the same HTTP map . The syntax for the regular expression field is proxy-specific. When [using Envoy](/consul/docs/connect/proxies/envoy), refer to [the documentation for Envoy v1.11.2 or newer](https://github.com/google/re2/wiki/Syntax) or [the documentation for Envoy v1.11.1 or older](https://en.cppreference.com/w/cpp/regex/ecmascript), depending on the version of Envoy you use. + +#### Values + +- Default: None +- Data type: String + +### `Routes[].Match{}.HTTP{}.Header[].Invert` + +Specifies that the logic for the HTTP header match should be inverted. Requests with matching criteria are not routed. + +#### Values + +- Default: `false` +- Data type: Boolean + +### `Routes[].Match{}.HTTP{}.QueryParam` + +Specifies information to match to on HTTP query parameters. When more than one field is configured, all criteria must match for the service routing to apply. + +When using this field, do not configure `Present`, `Exact`, and `Regex` in a single map. You can use only one of these fields at a time when configuring match criteria for HTTP query parameters, as they are mutually exclusive with one another. + +#### Values + +- Default: None +- Data type: List of maps. Each map can contain one or more of the following parameters: + + - [`Name`](#routes-match-http-queryparam-name) + - [`Present`](#routes-match-http-queryparam-present) + - [`Exact`](#routes-match-http-queryparam-exact) + - [`Regex`](#routes-match-http-queryparam-regex) + +### `Routes[].Match{}.HTTP{}.QueryParam[].Name` + +Specifies the name of the HTTP query parameter to match. This value is required when using [`Routes[].Match{}.HTTP{}.QueryParam`](#routes-match-http-queryparam). + +#### Values + +- Default: None +- Data type: String + +### `Routes[].Match{}.HTTP{}.QueryParam[].Present` + +Specifies that a request matches when the value in the `Name` field is present anywhere in the HTTP query parameter. When using this field, do not configure `Exact` or `Regex` in the same map. + +#### Values + +- Default: `false` +- Data type: Boolean + +### `Routes[].Match{}.HTTP{}.QueryParam[].Exact` + +Specifies that a request matches when the query parameter with the given name is this exact value. When using this field, do not configure `Present` or `Regex` in the same map. + +#### Values + +- Default: None +- Data type: String + +### `Routes[].Match{}.HTTP{}.QueryParam[].Regex` + +Specifies that a request matches when the query parameter with the given name matches this regular expression. When using this field, do not configure `Present` or `Exact` in the same map. The syntax for the regular expression field is proxy-specific. When [using Envoy](/consul/docs/connect/proxies/envoy), refer to [the documentation for Envoy v1.11.2 or newer](https://github.com/google/re2/wiki/Syntax) or [the documentation for Envoy v1.11.1 or older](https://en.cppreference.com/w/cpp/regex/ecmascript), depending on the version of Envoy you use. + +#### Values + +- Default: None +- Data type: String + +### `Routes[].Destination` + +Specifies the target service to route matching requests to, as well as behavior for the request to follow when routed. + +#### Values + +- Default: None +- Data type: Map containing one or more of the following parameters: + + - [`Service`](#routes-destination-service) + - [`ServiceSubset`](#routes-destination-servicesubset) + - [`Namespace`](#routes-destination-namespace) + - [`Partition`](#routes-destination-partition) + - [`PrefixRewrite`](#routes-destination-prefixrewrite) + - [`RequestTimeout`](#routes-destination-requesttimeout) + - [`IdleTimeout`](#routes-destination-idletimeout) + - [`NumRetries`](#routes-destination-numretries) + - [`RetryOnConnectFailure`](#routes-destination-retryonconnectfailure) + - [`RetryOn`](#routes-destination-retryon) + - [`RetryOnStatusCodes`](#routes-destination-retryonstatuscodes) + - [`RequestHeaders`](#routes-destination-requestheaders) + - [`ResponseHeaders`](#routes-destination-responseheaders) + +### `Routes[].Destination{}.Service` + +Specifies the name of the service to resolve. If this parameter is not specified, the default service name is inherited from the configuration entry’s [`Name` field](#name). + +#### Values + +- Default: None +- Data type: String + +### `Routes[].Destination{}.ServiceSubset` + +Specifies a named subset of the given service to resolve instead of the one defined as that service's `DefaultSubset` in the [service resolver configuration entry](/consul/docs/connect/config-entries/service-resolver). If this parameter is not specified, the default subset is used. + +#### Values + +- Default: None +- Data type: String + +### `Routes[].Destination{}.Namespace` + +Specifies the Consul namespace to resolve the service from instead of the current namespace. If this parameter is not specified, the current namespace is used. + +#### Values + +- Default: None +- Data type: String + +### `Routes[].Destination{}.Partition` + +Specifies the Consul admin partition to resolve the service from instead of the current partition. If this parameter is not specified, the current partition is used. + +#### Values + +- Default: None +- Data type: String + +### `Routes[].Destination{}.PrefixRewrite` + +Specifies rewrites to the HTTP request path before proxying it to its final destination. This field requires that either [`Routes[].Match{}.HTTP{}.PathPrefix`](#routes-match-http-pathprefix) or [`Routes[].Match{}.HTTP{}.PathExact`](#routes-match-http-pathexact) be configured on this route. + +#### Values + +- Default: None +- Data type: String + +### `Routes[].Destination{}.RequestTimeout` + +Specifies the total amount of time permitted for the entire downstream request to be processed, including retry attempts. + +#### Values + +- Default: `0` +- Data type: Integer + +### `Routes[].Destination{}.IdleTimeout` + +Specifies the total amount of time permitted for the request stream to be idle. + +#### Values + +- Default: `0` +- Data type: Integer + +### `Routes[].Destination{}.NumRetries` + +Specifies the number of times to retry the request when a retry condition occurs. Configure this field and other retry fields in `Destination` to configure the logic for retry attempts. For examples, refer to the [retry logic example configurations](#retry-logic). You cannot set the value to `0`. To disable retries, unset all other retry settings: `RetryOnConnectFailure`, `RetryOn`, `RetryOnStatusCodes`. + +#### Values + +- Default: `1` +- Data type: Integer + +### `Routes[].Destination{}.RetryOnConnectFailure` + +Specifies that connection failure errors that trigger a retry request. Configure this field and other retry fields in `Destination` to configure the logic for retry attempts. For examples, refer to the [retry logic example configurations](#retry-logic). + +#### Values + +- Default: `false` +- Data type: Boolean + +### `Routes[].Destination{}.RetryOn[]` + +Specifies a list of conditions for Consul to retry requests based on the response from an upstream service. Configure this field and other retry fields in the `Destination` object to configure the logic for retry attempts. For examples, refer to the [retry logic example configurations](#retry-logic). + +The following retry conditions are supported: + +| Conditions | Description | +| :------------------- | :------------------------------------------------------------------------------------------------------- | +| `5xx` | Consul retries the request when an upstream responds with any 5xx error code or does not respond at all. | +| `gateway-error` | Consul retries the request when the upstream responds with a 502, 503, or 504 error. | +| `reset` | Consul retries the request when the upstream does not respond at all. | +| `connect-failure` | Consul retries the request when the connection to the upstream fails. | +| `envoy-ratelimited` | Consul retries the request when the header `x-envoy-ratelimited` is present. | +| `retriable-4xx` | Consul retries the request when the upstream responds with a retriable 4xx code. | +| `refused-stream` | Consul retries the request when the upstream resets the stream with a `REFUSED_STREAM` error code. | +| `cancelled` | Consul retries the request when the gRPC status code in the response headers is `cancelled`. | +| `deadline-exceeded` | Consul retries the request when the gRPC status code in the response headers is `deadline-exceeded`. | +| `internal` | Consul retries the request when the gRPC status code in the response headers is `internal`. | +| `resource-exhausted` | Consul retries the request when the gRPC status code in the response headers is `resource-exhausted`. | +| `unavailable` | Consul retries the request when the gRPC status code in the response headers is `unavailable`. | + +#### Values + +- Default: None +- Data type: List of strings. Strings must match one of the following values: + + - `5xx` + - `gateway-error` + - `reset` + - `connect-failure` + - `envoy-ratelimited` + - `retriable-4xx` + - `refused-stream` + - `cancelled` + - `deadline-exceeded` + - `internal` + - `resource-exhausted` + - `unavailable` + +### `Routes[].Destination{}.RetryOnStatusCodes` + +Specifies a list of integers for [HTTP response status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) that trigger a retry request. Configure this field and other retry fields in `Destination` to configure the logic for retry attempts. For examples, refer to the [retry logic example configurations](#retry-logic) + +#### Values + +- Default: None +- Data type: List of integers + +### `Routes[].Destination{}.RequestHeaders` + +Specifies a set of HTTP-specific header modification rules applied to requests routed with the service router. You cannot configure request headers if the listener protocol is set to `tcp`. + +#### Values + +- Default: None +- Values: Object containing one or more fields that define header modification rules: + - `Add`: Map of one or more key-value pairs. + - `Set`: Map of one or more key-value pairs. + - `Remove`: Map of one or more key-value pairs. + +The following table describes how to configure values for request headers: + +| Rule | Description | Type | +| --- | --- | --- | +| `Add` | Defines a set of key-value pairs to add to the header. Use header names as the keys. Header names are not case-sensitive. If header values with the same name already exist, the value is appended and Consul applies both headers. You can [use variable placeholders](#use-variable-placeholders). | map of strings | +| `Set` | Defines a set of key-value pairs to add to the request header or to replace existing header values with. Use header names as the keys. Header names are not case-sensitive. If header values with the same names already exist, Consul replaces the header values. You can [use variable placeholders](#use-variable-placeholders). | map of strings | +| `Remove` | Defines a list of headers to remove. Consul removes only headers containing exact matches. Header names are not case-sensitive. | list of strings | + +#### Use variable placeholders + +For `Add` and `Set`, if the service is configured to use Envoy as the proxy, the value may contain variables to interpolate dynamic metadata into the value. For example, using the variable `%DOWNSTREAM_REMOTE_ADDRESS%` in your configuration entry allows you to pass a value that is generated when the routing occurs. + +### `Routes[].Destination{}.ResponseHeaders` + +Specifies a set of HTTP-specific header modification rules applied to responses routed with the service router. You cannot configure request headers if the listener protocol is set to `tcp`. + +#### Values + +- Default: None +- Values: Object containing one or more fields that define header modification rules: + - `Add`: Map of one or more string key-value pairs. + - `Set`: Map of one or more string key-value pairs. + - `Remove`: Map of one or more string key-value pairs. + +The following table describes how to configure values for response headers: + +| Rule | Description | Type | +| --- | --- | --- | +| `Add` | Defines a set of key-value pairs to add to the header. Use header names as the keys. Header names are not case-sensitive. If header values with the same name already exist, the value is appended and Consul applies both headers. You can [use variable placeholders](#use-variable-placeholders). | map of strings | +| `Set` | Defines a set of key-value pairs to add to the request header or to replace existing header values with. Use header names as the keys. Header names are not case-sensitive. If header values with the same names already exist, Consul replaces the header values. You can [use variable placeholders](#use-variable-placeholders). | map of strings | +| `Remove` | Defines a list of headers to remove. Consul removes only headers containing exact matches. Header names are not case-sensitive. | list of strings | + +#### Use variable placeholders + +For `Add` and `Set`, if the service is configured to use Envoy as the proxy, the value may contain variables to interpolate dynamic metadata into the value. For example, using the variable `%DOWNSTREAM_REMOTE_ADDRESS%` in your configuration entry allows you to pass a value that is generated when the routing occurs. + + + + + +### `apiVersion` + +Kubernetes-only parameter that specifies the version of the Consul API that the configuration entry maps to Kubernetes configurations. The value must be `consul.hashicorp.com/v1alpha1`. + +### `kind` + +Specifies the type of configuration entry to implement. + +#### Values + +- Default: None +- This field is required. +- Data type: String value that must be set to `ServiceRouter`. + +### `metadata.name` + +Specifies a name for the configuration entry. The name is metadata that you can use to reference the configuration entry when performing Consul operations, such as applying a configuration entry to a specific cluster. + +#### Values + +- Default: None +- Data type: String + +### `metadata.namespace` + +Specifies the Consul namespace to use for resolving the service. You can map Consul namespaces to Kubernetes Namespaces in different ways. Refer to [Custom Resource Definitions (CRDs) for Consul on Kubernetes](/consul/docs/k8s/crds#consul-enterprise) for additional information. + +#### Values + +- Default: None +- Data type: String + +### `spec` + +Map that contains the details about the `ServiceRouter` configuration entry. The `apiVersion`, `kind`, and `metadata` fields are siblings of the spec field. All other configurations are children. + +#### Values + +- Default: None +- This field is required. +- Data type: Object containing [`spec.routes`](#spec-routes) configuration + +### `spec.meta` + +Specifies key-value pairs to add to the KV store. + +#### Values + +- Default: none +- Data type: Map of one or more key-value pairs + - keys: String + - values: String, integer, or float + +### `spec.routes` + +Defines the possible routes for L7 requests. Consul evaluates traffic against the list of routes in their order of appearance in the configuration entry. When multiple routes satisfy the request, Consul uses the first route that matches. Traffic that fails to match any of the provided routes is routed to the default service. + +#### Values + +- Default: None +- Data type: List that can contain the following parameters: + +- [`match`](#spec-routes-match) +- [`destination`](#spec-routes-destination) + +### `spec.routes[].match` + +Describes a set of criteria that Consul compares incoming L7 traffic with. If empty or omitted, it acts as a catch-all. + +#### Values + +- Default: None +- Data type: Map that contains the [`spec.routes[].match.http`](#spec-routes-match-http) parameter. + +### `spec.routes[].match.http` + +Specifies a set of HTTP criteria used to evaluate incoming L7 traffic for matches. + +When matching on the HTTP request path, you can only match on one path at a time. Do not configure `pathExact`, `pathPrefix`, and `pathRegex` in a single HTTP map. + +#### Values + +- Default: None +- Data type: Map that can contain the following parameters: + + - [`pathExact`](#spec-routes-match-http-pathexact) + - [`pathPrefix`](#spec-routes-match-http-pathprefix) + - [`pathRegex`](#spec-routes-match-http-pathregex) + - [`methods`](#spec-routes-match-http-methods) + - [`header`](#spec-routes-match-http-header) + - [`queryParam`](#spec-routes-match-http-queryparam) + +### `spec.routes[].match.http.pathExact` + +Specifies the exact path to match on the HTTP request path. When using this field, do not configure `pathPrefix` or `pathRegex` in the same HTTP map. + +#### Values + +- Default: None +- Data type: String + +### `spec.routes[].match.http.pathPrefix` + +Specifies the path prefix to match on the HTTP request path. When using this field, do not configure `pathExact` or `pathRegex` in the same HTTP map. + +#### Values + +- Default: None +- Data type: String + +### `spec.routes[].match.http.pathRegex` + +Specifies a regular expression to match on the HTTP request path. When using this field, do not configure `pathExact` or `pathPrefix` in the same HTTP map. The syntax for the regular expression field is proxy-specific. When [using Envoy](/consul/docs/connect/proxies/envoy), refer to [the documentation for Envoy v1.11.2 or newer](https://github.com/google/re2/wiki/Syntax) or [the documentation for Envoy v1.11.1 or older](https://en.cppreference.com/w/cpp/regex/ecmascript), depending on the version of Envoy you use. + +#### Values + +- Default: None +- Data type: String + +### `spec.routes[].match.http.methods` + +Specifies HTTP methods that the match applies to. If not specified, the request matches on all HTTP methods. If provided, the name must be a valid method formatted as a string. + +String values must be a valid [HTTP request method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods). + +#### Values + +- Default: None +- Data type: List of strings. Each string must match one of the following values: + - `GET` + - `HEAD` + - `POST` + - `PUT` + - `DELETE` + - `CONNECT` + - `OPTIONS` + - `TRACE` + - `PATCH` + +### `spec.routes[].match.http.header` + +Specifies information to match to in the HTTP request header. When more than one field is configured, all criteria must match for the service routing to apply. + +When using this field, do not configure `present`, `exact`, `prefix`, `suffix`, and `regex` in the same HTTP map. You can use only one of these fields at a time when configuring match criteria for HTTP headers, as they are mutually exclusive with one another. + +#### Values + +- Default: None +- Data type: List containing one or more of the following parameters: -If a router is not explicitly configured or is configured with no routes then -the system behaves as if a router were configured sending all traffic to a -service of the same name. + - [`name`](#spec-routes-match-http-header-name) + - [`present`](#spec-routes-match-http-header-present) + - [`exact`](#spec-routes-match-http-header-exact) + - [`prefix`](#spec-routes-match-http-header-prefix) + - [`suffix`](#spec-routes-match-http-header-suffix) + - [`regex`](#spec-routes-match-http-header-regex) + - [`invert`](#spec-routes-match-http-header-invert) -## Requirements +### `spec.routes[].match.http.header.name` -- Consul [service mesh](/consul/docs/connect/configuration) enabled services -- Service to service communication over the protocol `http` +Specifies the name of the HTTP header to match. This field is required when using [`spec.routes[].match.http.header`](#spec-routes-match-http-header). -## Interaction with other Config Entries +#### Values -- Service router config entries are a component of [L7 Traffic - Management](/consul/docs/connect/l7-traffic). +- Default: None +- Data type: String -- Service router config entries are restricted to only services that define - their protocol as HTTP-based via a corresponding - [`service-defaults`](/consul/docs/connect/config-entries/service-defaults) config - entry or globally via - [`proxy-defaults`](/consul/docs/connect/config-entries/proxy-defaults) . +### `spec.routes[].match.http.header.present` -- Any route destination that omits the `ServiceSubset` field is eligible for - splitting via a - [`service-splitter`](/consul/docs/connect/config-entries/service-splitter) should - one be configured for that service, otherwise resolution proceeds according - to any configured - [`service-resolver`](/consul/docs/connect/config-entries/service-resolver). +Specifies that a request matches when the value in the `Name` field is present anywhere in the HTTP header. When using this field, do not configure `exact`, `prefix`, `suffix`, or `regex` in the same HTTP map. -## UI +#### Values -Once a `service-router` is successfully entered, you can view it in the UI. Service routers, service splitters, and service resolvers can all be viewed by clicking on your service then switching to the _routing_ tab. +- Default: `false` +- Data type: Boolean -![screenshot of service router in the UI](/img/l7-routing/Router.png) +### `spec.routes[].match.http.header.exact` -## Sample Config Entries +Specifies that a request matches when the header with the given name is this exact value. When using this field, do not configure `present`, `prefix`, `suffix`, or `regex` in the same HTTP map. + +#### Values + +- Default: None +- Data type: String + +### `spec.routes[].match.http.header.prefix` + +Specifies that a request matches when the header with the given name has this prefix. When using this field, do not configure `present`, `exact`, `suffix`, or `regex` in the same HTTP map. + +#### Values + +- Default: None +- Data type: String + +### `spec.routes[].match.http.header.suffix` + +Specifies that a request matches when the header with the given name has this suffix. When using this field, do not configure `present`, `exact`, `prefix`, or `regex` in the same HTTP map. + +#### Values + +- Default: None +- Data type: String + +### `spec.routes[].match.http.header.regex` + +Specifies that a request matches when the header with the given name matches this regular expression. When using this field, do not configure `present`, `exact`, `prefix`, or `suffix` in the same HTTP map . The syntax for the regular expression field is proxy-specific. When [using Envoy](/consul/docs/connect/proxies/envoy), refer to [the documentation for Envoy v1.11.2 or newer](https://github.com/google/re2/wiki/Syntax) or [the documentation for Envoy v1.11.1 or older](https://en.cppreference.com/w/cpp/regex/ecmascript), depending on the version of Envoy you use. + +#### Values + +- Default: None +- Data type: String + +### `spec.routes[].match.http.header.invert` + +Specifies that the logic for the HTTP header match should be inverted. Requests with matching criteria are not routed. + +#### Values + +- Default: `false` +- Data type: Boolean + +### `spec.routes[].match.http.queryParam` + +Specifies information to match to on HTTP query parameters. When more than one field is configured, all criteria must match for the service routing to apply. + +When using this field, do not configure `present`, `exact`, and `regex` in a single map. You can use only one of these fields at a time when configuring match criteria for HTTP query parameters, as they are mutually exclusive with one another. + +#### Values + +- Default: None +- Data type: List of maps. Each map can contain one or more of the following parameters: + + - [`name`](#spec-routes-match-http-queryparam-name) + - [`present`](#spec-routes-match-http-queryparam-present) + - [`regex`](#spec-routes-match-http-queryparam-regex) + +### `spec.routes[].match.http.queryParam[].name` + +Specifies the name of the HTTP query parameter to match. This value is required when using [`spec.routes[].match.http.queryParam`](#spec-routes-match-http-queryparam). + +#### Values + +- Default: None +- Data type: String + +### `spec.routes[].match.http.queryParam[].present` + +Specifies that a request matches when the value in the `name` field is present anywhere in the HTTP query parameter. When using this field, do not configure `exact` or `regex` in the same map. + +#### Values + +- Default: `false` +- Data type: Boolean + +### `spec.routes[].match.http.queryParam[].exact` + +Specifies that a request matches when the query parameter with the given name is this exact value. When using this field, do not configure `present` or `regex` in the same map. + +#### Values + +- Default: None +- Data type: String + +### `spec.routes[].match.http.queryParam[].regex` + +Specifies that a request matches when the query parameter with the given name matches this regular expression. When using this field, do not configure `present` or `exact` in the same map. The syntax for the regular expression field is proxy-specific. When [using Envoy](/consul/docs/connect/proxies/envoy), refer to [the documentation for Envoy v1.11.2 or newer](https://github.com/google/re2/wiki/Syntax) or [the documentation for Envoy v1.11.1 or older](https://en.cppreference.com/w/cpp/regex/ecmascript), depending on the version of Envoy you use. + +#### Values + +- Default: None +- Data type: String + +### `spec.routes[].destination` + +Specifies the target service to route matching requests to, as well as behavior for the request to follow when routed. + +#### Values + +- Default: None +- Data type: Map containing one or more of the following parameters: + + - [`service`](#spec-routes-destination-service) + - [`serviceSubset`](#spec-routes-destination-servicesubset) + - [`namespace`](#spec-routes-destination-namespace) + - [`partition`](#spec-routes-destination-partition) + - [`prefixRewrite`](#spec-routes-destination-prefixrewrite) + - [`requestTimeout`](#spec-routes-destination-requesttimeout) + - [`numRetries`](#spec-routes-destination-numretries) + - [`numRetries`](#spec-routes-destination-numretries) + - [`retryOnConnectFailure`](#spec-routes-destination-retryonconnectfailure) + - [`retryOn`](#spec-routes-destination-retryon) + - [`retryOnStatusCodes`](#spec-routes-destination-retryonstatuscodes) + - [`requestHeaders`](#spec-routes-destination-requestheaders) + - [`responseHeaders`](#spec-routes-destination-responseheaders) + +### `spec.routes[].destination.service` + +Specifies the name of the service to resolve. If this parameter is not specified, the default service name is inherited from the configuration entry’s [`metadata.name` field](#metadata-name). + +#### Values + +- Default: None +- Data type: String + +### `spec.routes[].destination.serviceSubset` + +Specifies a named subset of the given service to resolve instead of the one defined as that service's `defaultSubset` in the [service resolver configuration entry](/consul/docs/connect/config-entries/service-resolver). If this parameter is not specified, the default subset is used. + +#### Values + +- Default: None +- Data type: String + +### `spec.routes[].destination.namespace` + +Specifies the Consul namespace to resolve the service from instead of the current namespace. If this parameter is not specified, the current namespace is used. + +#### Values + +- Default: None +- Data type: String + +### `spec.routes[].destination.partition` + +Specifies the Consul admin partition to resolve the service from instead of the current partition. If this parameter is not specified, the current partition is used. + +#### Values + +- Default: None +- Data type: String + +### `spec.routes[].destination.prefixRewrite` + +Specifies rewrites to the HTTP request path before proxying it to its final destination. This field requires that either [`spec.routes[].match.http.pathPrefix`](#spec-routes-match-http-pathprefix) or [`spec.routes[].match.http.pathExact`](#spec-routes-match-http-pathexact) be configured on this route. + +#### Values + +- Default: None +- Data type: String + +### `spec.routes[].destination.requestTimeout` + +Specifies the total amount of time permitted for the entire downstream request to be processed, including retry attempts. + +#### Values + +- Default: `0` +- Data type: Integer + +### `spec.routes[].destination.idleTimeout` + +Specifies the total amount of time permitted for the request stream to be idle. + +#### Values + +- Default: `0` +- Data type: Integer + +### `spec.routes[].destination.numRetries` + +Specifies the number of times to retry the request when a retry condition occurs. Configure this field and other retry fields in `spec.routes.destination` to configure the logic for retry attempts. For examples, refer to the [retry logic example configurations](#retry-logic). You cannot set the value to `0`. To disable retries, unset all other retry settings: `retryOnConnectFailure`, `retryOn`, `retryOnStatusCodes`. + +#### Values + +- Default: `1` +- Data type: Integer + +### `spec.routes[].destination.retryOnConnectFailure` + +Specifies that connection failure errors that trigger a retry request. Configure this field and other retry fields in `spec.routes[].destination` to configure the logic for retry attempts. For examples, refer to the [retry logic example configurations](#retry-logic). + +#### Values + +- Default: `false` +- Data type: Boolean + +### `spec.routes[].destination.retryOn` + +Specifies a list of conditions for Consul to retry requests based on the response from an upstream service. Configure this field and other retry fields in the `spec.routes[].destination` object to configure the logic for retry attempts. For examples, refer to the [retry logic example configurations](#retry-logic). + +The following retry conditions are supported: + +| Conditions | Description | +| :------------------- | :------------------------------------------------------------------------------------------------------- | +| `5xx` | Consul retries the request when an upstream responds with any 5xx error code or does not respond at all. | +| `gateway-error` | Consul retries the request when the upstream responds with a 502, 503, or 504 error. | +| `reset` | Consul retries the request when the upstream does not respond at all. | +| `connect-failure` | Consul retries the request when the connection to the upstream fails. | +| `envoy-ratelimited` | Consul retries the request when the header `x-envoy-ratelimited` is present. | +| `retriable-4xx` | Consul retries the request when the upstream responds with a retriable 4xx code. | +| `refused-stream` | Consul retries the request when the upstream resets the stream with a `REFUSED_STREAM` error code. | +| `cancelled` | Consul retries the request when the gRPC status code in the response headers is `cancelled`. | +| `deadline-exceeded` | Consul retries the request when the gRPC status code in the response headers is `deadline-exceeded`. | +| `internal` | Consul retries the request when the gRPC status code in the response headers is `internal`. | +| `resource-exhausted` | Consul retries the request when the gRPC status code in the response headers is `resource-exhausted`. | +| `unavailable` | Consul retries the request when the gRPC status code in the response headers is `unavailable`. | + +#### Values + +- Default: None +- Data type: List of strings. Strings must match one of the following values: + + - `5xx` + - `gateway-error` + - `reset` + - `connect-failure` + - `envoy-ratelimited` + - `retriable-4xx` + - `refused-stream` + - `cancelled` + - `deadline-exceeded` + - `internal` + - `resource-exhausted` + - `unavailable` + +### `spec.routes[].destination.retryOnStatusCodes` + +Specifies a list of integers for [HTTP response status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) that trigger a retry request. Configure this field and other retry fields in `spec.routes[].destination` to configure the logic for retry attempts. For examples, refer to the [retry logic example configurations](#retry-logic) + +#### Values + +- Default: None +- Data type: List of integers + +### `spec.routes[].destination.requestHeaders` + +Specifies a set of HTTP-specific header modification rules applied to requests routed with the service router. You cannot configure request headers if the listener protocol is set to `tcp`. + +#### Values + +- Default: None +- Values: Object containing one or more fields that define header modification rules: + - `add`: Map of one or more key-value pairs. + - `set`: Map of one or more key-value pairs. + - `remove`: Map of one or more key-value pairs. + +The following table describes how to configure values for request headers: + +| Rule | Description | Type | +| --- | --- | --- | +| `add` | Defines a set of key-value pairs to add to the header. Use header names as the keys. Header names are not case-sensitive. If header values with the same name already exist, the value is appended and Consul applies both headers. You can [use variable placeholders](#use-variable-placeholders). | map of strings | +| `set` | Defines a set of key-value pairs to add to the request header or to replace existing header values with. Use header names as the keys. Header names are not case-sensitive. If header values with the same names already exist, Consul replaces the header values. You can [use variable placeholders](#use-variable-placeholders). | map of strings | +| `remove` | Defines a list of headers to remove. Consul removes only headers containing exact matches. Header names are not case-sensitive. | list of strings | + +#### Use variable placeholders + +For `add` and `set`, if the service is configured to use Envoy as the proxy, the value may contain variables to interpolate dynamic metadata into the value. For example, using the variable `%DOWNSTREAM_REMOTE_ADDRESS%` in your configuration entry allows you to pass a value that is generated when the routing occurs. + +### `spec.routes[].destination.responseHeaders` + +Specifies a set of HTTP-specific header modification rules applied to responses routed with the service router. You cannot configure request headers if the listener protocol is set to `tcp`. + +#### Values + +- Default: None +- Values: Object containing one or more fields that define header modification rules: + - `add`: Map of one or more string key-value pairs. + - `set`: Map of one or more string key-value pairs. + - `remove`: Map of one or more string key-value pairs. + +The following table describes how to configure values for response headers: + +| Rule | Description | Type | +| --- | --- | --- | +| `add` | Defines a set of key-value pairs to add to the header. Use header names as the keys. Header names are not case-sensitive. If header values with the same name already exist, the value is appended and Consul applies both headers. You can [use variable placeholders](#use-variable-placeholders). | map of strings | +| `set` | Defines a set of key-value pairs to add to the request header or to replace existing header values with. Use header names as the keys. Header names are not case-sensitive. If header values with the same names already exist, Consul replaces the header values. You can [use variable placeholders](#use-variable-placeholders). | map of strings | +| `remove` | Defines a list of headers to remove. Consul removes only headers containing exact matches. Header names are not case-sensitive. | list of strings | + +#### Use variable placeholders + +For `add` and `set`, if the service is configured to use Envoy as the proxy, the value may contain variables to interpolate dynamic metadata into the value. For example, using the variable `%DOWNSTREAM_REMOTE_ADDRESS%` in your configuration entry allows you to pass a value that is generated when the routing occurs. + + + + + +## Examples + +The following examples demonstrate common service router configuration patterns for specific use cases. ### Path prefix matching -Route HTTP requests with a path starting with `/admin` to a different service: +The following example routes HTTP requests for the `web` service to a service named `admin` when they have `/admin` at the start of their path. - + + ```hcl Kind = "service-router" @@ -66,10 +1325,13 @@ Routes = [ Service = "admin" } }, - # NOTE: a default catch-all will send unmatched traffic to "web" ] ``` + + + + ```yaml apiVersion: consul.hashicorp.com/v1alpha1 kind: ServiceRouter @@ -82,9 +1344,12 @@ spec: pathPrefix: /admin destination: service: admin - # NOTE: a default catch-all will send unmatched traffic to "web" ``` + + + + ```json { "Kind": "service-router", @@ -104,13 +1369,15 @@ spec: } ``` - + + -### Header/query parameter matching +### Match a header and query parameter -Route HTTP requests with a special URL parameter or header to a canary subset: +The following example routes HTTP traffic to the `web` service to a subset of `canary` instances when the requests have `x-debug` in either the header or the URL parameter. - + + ```hcl Kind = "service-router" @@ -148,10 +1415,13 @@ Routes = [ ServiceSubset = "canary" } }, - # NOTE: a default catch-all will send unmatched traffic to "web" ] ``` + + + + ```yaml apiVersion: consul.hashicorp.com/v1alpha1 kind: ServiceRouter @@ -175,9 +1445,12 @@ spec: destination: service: web serviceSubset: canary - # NOTE: a default catch-all will send unmatched traffic to "web" ``` + + + + ```json { "Kind": "service-router", @@ -219,14 +1492,15 @@ spec: } ``` - + + ### gRPC routing -Re-route a gRPC method to another service. Since gRPC method calls [are -HTTP/2](https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md), we can use an HTTP path match rule to re-route traffic: +The following example routes gRPC requests to the `invoice-generator`service when they come from an HTTP path that is exact match for `mycompany.BillingService/GenerateInvoice`. Because gRPC method calls use HTTP/2, you can use an HTTP path match rule to re-route traffic. - + + ```hcl Kind = "service-router" @@ -243,10 +1517,13 @@ Routes = [ Service = "invoice-generator" } }, - # NOTE: a default catch-all will send unmatched traffic to "billing" ] ``` + + + + ```yaml apiVersion: consul.hashicorp.com/v1alpha1 kind: ServiceRouter @@ -259,9 +1536,12 @@ spec: pathExact: /mycompany.BillingService/GenerateInvoice destination: service: invoice-generator - # NOTE: a default catch-all will send unmatched traffic to "billing" ``` + + + + ```json { "Kind": "service-router", @@ -281,21 +1561,25 @@ spec: } ``` - + + ### Retry logic -Enable retry logic by delegating this responsibility to Consul and the proxy. Review the [`ServiceRouteDestination`](#serviceroutedestination) block for more details. +The following example configures Consul so that when a request for the `orders` service passes through the service mesh, Consul routes the traffic to the `products` service or the `procurement` service based on the HTTP path that originated the request: - +- If it originates from the `/coffees` path, the request routes to the `products` service, times out after 15 seconds, and attempts 5 retries. +- If it originates from the `/orders` path, the request routes to the `procurement` services, times out after 10 seconds, and attempts 3 retries. + + ```hcl Kind = "service-router" Name = "orders" Routes = [ { - Match{ + Match { HTTP { PathPrefix = "/coffees" } @@ -303,14 +1587,14 @@ Routes = [ Destination { Service = "products" - RequestTimeout = "10s" - NumRetries = 3 + RequestTimeout = "15s" + NumRetries = 5 RetryOnConnectFailure = true RetryOn = ["reset"] } }, { - Match{ + Match { HTTP { PathPrefix = "/orders" } @@ -327,6 +1611,10 @@ Routes = [ ] ``` + + + + ```yaml apiVersion: consul.hashicorp.com/v1alpha1 kind: ServiceRouter @@ -339,8 +1627,8 @@ spec: pathExact: /coffees destination: service: products - requestTimeout: 10s - numRetries: 3 + requestTimeout: 15s + numRetries: 5 retryOnConnectFailure: true retryOn: ['reset'] - match: @@ -354,6 +1642,9 @@ spec: retryOn: ['reset'] ``` + + + ```json { @@ -367,8 +1658,8 @@ spec: } }, "Destination": { - "NumRetries": 3, - "RequestTimeout": "10s", + "NumRetries": 5, + "RequestTimeout": "15s", "RetryOnConnectFailure": true, "RetryOn": ["reset"], "Service": "procurement" @@ -392,413 +1683,6 @@ spec: } ``` - - -## Available Fields - -', - yaml: false, - }, - { - name: 'Namespace', - type: `string: "default"`, - enterprise: true, - description: - 'Specifies the namespace to which the configuration entry will apply.', - yaml: false, - }, - { - name: 'Partition', - type: `string: "default"`, - enterprise: true, - description: - 'Specifies the admin partition to which the configuration will apply.', - yaml: false, - }, - { - name: 'Meta', - type: 'map: nil', - description: - 'Specifies arbitrary KV metadata pairs. Added in Consul 1.8.4.', - yaml: false, - }, - { - name: 'metadata', - children: [ - { - name: 'name', - description: 'Set to the name of the service being configured.', - }, - { - name: 'namespace', - description: - 'If running Consul Open Source, the namespace is ignored (see [Kubernetes Namespaces in Consul OSS](/consul/docs/k8s/crds#consul-oss)). If running Consul Enterprise see [Kubernetes Namespaces in Consul Enterprise](/consul/docs/k8s/crds#consul-enterprise) for more details.', - }, - ], - hcl: false, - }, - { - name: 'Routes', - type: 'array', - description: `The list of routes to consider when - processing L7 requests. The first route to match in the list is terminal and - stops further evaluation. Traffic that fails to match any of the provided - routes will be routed to the default service.`, - children: [ - { - name: 'Match', - type: 'ServiceRouteMatch: ', - description: `A set of criteria that can - match incoming L7 requests. If empty or omitted it acts as a catch-all.`, - children: [ - { - name: 'HTTP', - type: 'ServiceRouteHTTPMatch: ', - description: `A set of [HTTP-specific match criteria](#serviceroutehttpmatch).`, - }, - ], - }, - { - name: 'Destination', - type: 'ServiceRouteDestination: ', - description: `Controls [how to proxy](#serviceroutedestination) the matching request(s) to a service.`, - }, - ], - }, - ]} -/> - -### `ServiceRouteHTTPMatch` - -
At most only one of `PathExact`, `PathPrefix`, or `PathRegex` may be configured.', - yaml: - 'Exact path to match on the HTTP request path.

At most only one of `pathExact`, `pathPrefix`, or `pathRegex` may be configured.', - }, - }, - { - name: 'PathPrefix', - type: 'string: ""', - description: { - hcl: - 'Path prefix to match on the HTTP request path.

At most only one of `PathExact`, `PathPrefix`, or `PathRegex` may be configured.', - yaml: - 'Path prefix to match on the HTTP request path.

At most only one of `pathExact`, `pathPrefix`, or `pathRegex` may be configured.', - }, - }, - { - name: 'PathRegex', - type: 'string: ""', - description: { - hcl: - 'Regular expression to match on the HTTP request path.

The syntax is [described below](#regular-expression-syntax).

At most only one of `PathExact`, `PathPrefix`, or `PathRegex` may be configured.', - yaml: - 'Regular expression to match on the HTTP request path.

The syntax is [described below](#regular-expression-syntax).

At most only one of `pathExact`, `pathPrefix`, or `pathRegex` may be configured.', - }, - }, - { - name: 'Methods', - type: 'array', - description: - 'A list of HTTP methods for which this match applies. If unspecified all HTTP methods are matched. If provided the names must be a valid [method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods).', - }, - { - name: 'Header', - type: 'array)', - description: - 'A set of criteria that can match on HTTP request headers. If more than one is configured all must match for the overall match to apply.', - children: [ - { - name: 'Name', - type: 'string: ', - description: 'Name of the header to match.', - }, - { - name: 'Present', - type: 'bool: false', - description: { - hcl: - 'Match if the header with the given name is present with any value.

At most only one of `Exact`, `Prefix`, `Suffix`, `Regex`, or `Present` may be configured.', - yaml: - 'Match if the header with the given name is present with any value.

At most only one of `exact`, `prefix`, `suffix`, `regex`, or `present` may be configured.', - }, - }, - { - name: 'Exact', - type: 'string: ""', - description: { - hcl: - 'Match if the header with the given name is this value.

At most only one of `Exact`, `Prefix`, `Suffix`, `Regex`, or `Present` may be configured.', - yaml: - 'Match if the header with the given name is this value.

At most only one of `exact`, `prefix`, `suffix`, `regex`, or `present` may be configured.', - }, - }, - { - name: 'Prefix', - type: 'string: ""', - description: { - hcl: - 'Match if the header with the given name has this prefix.

At most only one of `Exact`, `Prefix`, `Suffix`, `Regex`, or `Present` may be configured.', - yaml: - 'Match if the header with the given name has this prefix.

At most only one of `exact`, `prefix`, `suffix`, `regex`, or `present` may be configured.', - }, - }, - { - name: 'Suffix', - type: 'string: ""', - description: { - hcl: - 'Match if the header with the given name has this suffix.

At most only one of `Exact`, `Prefix`, `Suffix`, `Regex`, or `Present` may be configured.', - yaml: - 'Match if the header with the given name has this suffix.

At most only one of `exact`, `prefix`, `suffix`, `regex`, or `present` may be configured.', - }, - }, - { - name: 'Regex', - type: 'string: ""', - description: { - hcl: - 'Match if the header with the given name matches this pattern.

The syntax is [described below](#regular-expression-syntax).

At most only one of `Exact`, `Prefix`, `Suffix`, `Regex`, or `Present` may be configured.', - yaml: - 'Match if the header with the given name matches this pattern.

The syntax is [described below](#regular-expression-syntax).

At most only one of `exact`, `prefix`, `suffix`, `regex`, or `present` may be configured.', - }, - }, - { - name: 'Invert', - type: 'bool: false', - description: 'Inverts the logic of the match', - }, - ], - }, - { - name: 'QueryParam', - type: 'array)', - description: - 'A set of criteria that can match on HTTP query parameters. If more than one is configured all must match for the overall match to apply.', - children: [ - { - name: 'Name', - type: 'string: ', - description: 'The name of the query parameter to match on.', - }, - { - name: 'Present', - type: 'bool: false', - description: { - hcl: - 'Match if the query parameter with the given name is present with any value.

At most only one of `Exact`, `Regex`, or `Present` may be configured.', - yaml: - 'Match if the query parameter with the given name is present with any value.

At most only one of `exact`, `regex`, or `present` may be configured.', - }, - }, - { - name: 'Exact', - type: 'string: ""', - description: { - hcl: - 'Match if the query parameter with the given name is this value.

At most only one of `Exact`, `Regex`, or `Present` may be configured.', - yaml: - 'Match if the query parameter with the given name is this value.

At most only one of `exact`, `regex`, or `present` may be configured.', - }, - }, - { - name: 'Regex', - type: 'string: ""', - description: { - hcl: - 'Match if the query parameter with the given name matches this pattern.

The syntax is [described below](#regular-expression-syntax).

At most only one of `Exact`, `Regex`, or `Present` may be configured.', - yaml: - 'Match if the query parameter with the given name matches this pattern.

The syntax is [described below](#regular-expression-syntax).

At most only one of `exact`, `regex`, or `present` may be configured.', - }, - }, - ], - }, - ]} -/> - -### `ServiceRouteDestination` - -
This requires that either `Match.HTTP.PathPrefix` or `Match.HTTP.PathExact` be configured on this route.', - yaml: - 'Defines how to rewrite the HTTP request path before proxying it to its final destination.

This requires that either `match.http.pathPrefix` or `match.http.pathExact` be configured on this route.', - }, - }, - { - name: 'RequestTimeout', - type: 'duration: 0', - description: - 'The total amount of time permitted for the entire downstream request (and retries) to be processed.', - }, - { - name: 'IdleTimeout', - type: 'duration: 0', - description: - 'The total amount of time permitted for the request stream to be idle', - }, - { - name: 'NumRetries', - type: 'int: 1', - description: { - hcl: 'The number of times to retry the request when a retryable result occurs. You cannot set the value to `0`. To disable retries, unset all other retry settings (`RetryOnConnectFailure`, `RetryOn`, `RetryOnStatusCodes`)', - yaml: 'The number of times to retry the request when a retryable result occurs. You cannot set the value to `0`. To disable retries, unset all other retry settings (`retryOnConnectFailure`, `retryOn`, `retryOnStatusCodes`)', - } - }, - { - name: 'RetryOnConnectFailure', - type: 'bool: false', - description: 'Allows for connection failure errors to trigger a retry.', - }, - { - name: 'RetryOn', - type: 'array', - description: `Allows Consul to retry requests when they meet one of the following sets of conditions: - \`5xx\`, \`gateway-error\`, \`reset\`, \`connect-failure\`, \`envoy-ratelimited\`, \`retriable-4xx\`, - \`refused-stream\`, \`cancelled\`, \`deadline-exceeded\`, \`internal\`, \`resource-exhausted\`, or \`unavailable\``, - }, - { - name: 'RetryOnStatusCodes', - type: 'array', - description: - 'A list of HTTP response status codes that are eligible for retry.', - }, - { - name: 'RequestHeaders', - type: 'HTTPHeaderModifiers: ', - description: `A set of [HTTP-specific header modification rules](/consul/docs/connect/config-entries/service-router#httpheadermodifiers) - that will be applied to requests routed to this service. - This cannot be used with a \`tcp\` listener.`, - }, - { - name: 'ResponseHeaders', - type: 'HTTPHeaderModifiers: ', - description: `A set of [HTTP-specific header modification rules](/consul/docs/connect/config-entries/service-router#httpheadermodifiers) - that will be applied to responses from this service. - This cannot be used with a \`tcp\` listener.`, - }, - ]} -/> - -### `HTTPHeaderModifiers` - -: optional', - description: `The set of key/value pairs that specify header values to add. - Use header names as keys. Header names are _not_ case-sensitive. - If header values with the same name already exist, the value set here will - be appended and both will be present. - If Envoy is used as the proxy, the value may contain - [variable placeholders](https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_conn_man/headers#custom-request-response-headers) for example - \`%DOWNSTREAM_REMOTE_ADDRESS%\` to interpolate dynamic request - metadata into the value added.`, - }, - { - name: 'Set', - type: 'map: optional', - description: `The set of key/value pairs that specify header values to add. - Use header names as keys. Header names are _not_ case-sensitive. - If header values with the same name already exist, the value set here will - _replace_ them. - If Envoy is used as the proxy, the value may contain - [variable placeholders](https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_conn_man/headers#custom-request-response-headers) for example - \`%DOWNSTREAM_REMOTE_ADDRESS%\` to interpolate dynamic request - metadata into the value added.`, - }, - { - name: 'Remove', - type: 'array: optional', - description: `The set of header names to remove. Only headers - whose names are a case-insensitive exact match will be removed`, - }, - ]} -/> - -## ACLs - -Configuration entries may be protected by [ACLs](/consul/docs/security/acl). - -Reading a `service-router` config entry requires `service:read` on the resource. - -Creating, updating, or deleting a `service-router` config entry requires -`service:write` on the resource and `service:read` on any other service referenced by -name in these fields: - -- [`Routes[].Destination.Service`](#service) - -## Regular Expression Syntax - -The actual syntax of the regular expression fields described here is entirely -proxy-specific. - -When using [Envoy](/consul/docs/connect/proxies/envoy) as a proxy (the only supported proxy in Kubernetes), -the syntax for these fields is version specific: -| Envoy Version | Syntax | -| --------------- | ------------------------------------------------------------------- | -| 1.11.2 or newer | [documentation](https://github.com/google/re2/wiki/Syntax) | -| 1.11.1 or older | [documentation](https://en.cppreference.com/w/cpp/regex/ecmascript) | + + \ No newline at end of file