Kubernetes (K8s) [1]¶
Feature of: Service Discovery
Ocelot will call the K8s endpoints API in a given namespace to get all of the endpoints for a pod and then load balance across them. Ocelot used to use the services API to send requests to the K8s service but this was changed in pull request 1134 because the service did not load balance as expected.
Our NuGet Ocelot.Provider.Kubernetes extension package is based on the KubeClient package. For a comprehensive understanding, it is essential refer to the KubeClient documentation.
Install¶
The first thing you need to do is install the package that provides
support in Ocelot:
Install-Package Ocelot.Provider.Kubernetes
AddKubernetes(bool) method¶
public static class OcelotBuilderExtensions
{
public static IOcelotBuilder AddKubernetes(this IOcelotBuilder builder, bool usePodServiceAccount = true);
}
This extension-method adds K8s services with or without using a pod service account. Then add the following to your Program:
builder.Services
.AddOcelot(builder.Configuration)
.AddKubernetes(); // usePodServiceAccount is true
If you have services deployed in Kubernetes, you will normally use the naming service to access them.
By default the
useServiceAccountargument is true, which means that Service Account using Pod to access the service of the K8s cluster needs to be Service Account based on RBAC authorization:You can replicate a Permissive using RBAC role bindings (see Permissive RBAC Permissions), K8s API server and token will read from pod.
kubectl create clusterrolebinding permissive-binding --clusterrole=cluster-admin --user=admin --user=kubelet --group=system:serviceaccounts
Finally, it creates the KubeClient from pod service account.
When the
useServiceAccountargument is false, you need to provide KubeClientOptions to create KubeClient using them. You have to bind the options configuration section for the DIIOptions<KubeClientOptions>interface or register a custom action to initialize the options:Action<KubeClientOptions> configureKubeClient = opts => { opts.ApiEndPoint = new UriBuilder("https", "my-host", 443).Uri; opts.AccessToken = "my-token"; opts.AuthStrategy = KubeAuthStrategy.BearerToken; opts.AllowInsecure = true; }; builder.Services .AddOptions<KubeClientOptions>() .Configure(configureKubeClient); // manual binding options via IOptions<KubeClientOptions> builder.Services .AddOcelot(builder.Configuration) .AddKubernetes(false); // don't use pod service account, and IOptions<KubeClientOptions> is reused
Note, this could also be written like this (shortened version):
builder.Services .AddKubeClientOptions(opts => { opts.ApiEndPoint = new UriBuilder("https", "my-host", 443).Uri; opts.AuthStrategy = KubeAuthStrategy.BearerToken; opts.AccessToken = "my-token"; opts.AllowInsecure = true; }) .AddOcelot(builder.Configuration) .AddKubernetes(false); // don't use pod service account, and client options provided via AddKubeClientOptions
Finally, it creates the KubeClient from your options.
Note 1: For understanding the
IOptions<TOptions>interface, please refer to the Microsoft Learn documentation: Options pattern in .NET.Note 2: Please consider this Case 2 as an example of manual setup when you do not use a pod service account. We recommend using our official extension method, which receives an
Action<KubeClientOptions>argument with your options: refer to the AddKubernetes(Action<KubeClientOptions>) method 2 below.
AddKubernetes(Action<KubeClientOptions>) method [2]¶
public static class OcelotBuilderExtensions
{
public static IOcelotBuilder AddKubernetes(this IOcelotBuilder builder, Action<KubeClientOptions> configureOptions, /*optional params*/);
}
This extension method adds K8s services without using a pod service account, explicitly calling an action to initialize configuration options for KubeClient. It operates in two modes:
If
configureOptionsis provided (action is not null), it calls the action, ignoring all optional arguments.Action<KubeClientOptions> configureKubeClient = opts => { opts.ApiEndPoint = new UriBuilder("https", "my-host", 443).Uri; // ... }; builder.Services .AddOcelot(builder.Configuration) .AddKubernetes(configureKubeClient); // without optional arguments
Note: Optional arguments do not make sense; all settings are defined inside the
configureKubeClientaction.
If
configureOptionsis not provided (action is null), it reads the globalServiceDiscoveryProviderConfiguration options and reuses them to initialize the following properties:ApiEndPoint,AccessToken, andKubeNamespace, finally initializing the rest of the properties with optional arguments.builder.Services .AddOcelot(builder.Configuration) .AddKubernetes(null, allowInsecure: true, /*optional args*/) // shortened version // or .AddKubernetes(configureOptions: null, allowInsecure: true, /*optional args*/); // long version
Note: Optional arguments must be used here in addition to the options coming from the global
ServiceDiscoveryProviderConfiguration. Find the comprehensive documentation in the C# code of the AddKubernetes methods.
Configuration¶
The following examples show how to set up a route that will work in Kubernetes.
The most important thing is the ServiceName which is made up of the Kubernetes service name.
We also need to set up the ServiceDiscoveryProvider in GlobalConfiguration.
Kube provider¶
The example here shows a typical configuration:
"Routes": [
{
"ServiceName": "my-service",
// ...
}
],
"GlobalConfiguration": {
"ServiceDiscoveryProvider": {
"Scheme": "https",
"Host": "my-host",
"Port": 443,
"Token": "my-token",
"Namespace": "Dev",
"Type": "Kube"
}
}
Service deployment in Dev namespace, and discovery provider type is Kube, you also can set PollKube provider type.
Note 1:
Scheme,Host,Port, andTokenare not used ifusePodServiceAccountis true when KubeClient is created from a pod service account. Please refer to the Install section for technical details.Note 2: The
Kubeprovider searches for the service entry usingServiceNameand then retrieves the first available port from theEndpointSubsetV1.Portscollection. Therefore, if the port name is not specified, the default downstream scheme will behttp; Please refer to the Downstream Scheme vs Port Names 3 section for technical details.
PollKube provider¶
You use Ocelot to poll Kubernetes for latest service information rather than per request. If you want to poll Kubernetes for the latest services rather than per request (default behaviour) then you need to set the following configuration:
"ServiceDiscoveryProvider": {
"Namespace": "dev",
"Type": "PollKube",
"PollingInterval": 100 // ms
}
The polling interval is in milliseconds and tells Ocelot how often to call Kubernetes for changes in service configuration.
Note, there are tradeoffs here. If you poll Kubernetes, it is possible Ocelot will not know if a service is down depending on your polling interval and you might get more errors than if you get the latest services per request. This really depends on how volatile your services are. We doubt it will matter for most people and polling may give a tiny performance improvement over calling Kubernetes per request. There is no way for Ocelot to work these out for you, except perhaps through a discussion.
Global vs Route levels¶
If your downstream service resides in a different namespace, you can override the global setting at the route-level by specifying a ServiceNamespace:
"Routes": [
{
"ServiceName": "my-service",
"ServiceNamespace": "my-namespace"
}
]
Downstream Scheme vs Port Names [3]¶
Kubernetes configuration permits the definition of multiple ports with names for each address of an endpoint subset.
When binding multiple ports, you assign a name to each subset port.
To allow the Kube provider to recognize the desired port by its name, you need to specify the DownstreamScheme with the port’s name;
if not, the collection’s first port entry will be chosen by default.
For instance, consider a service on Kubernetes that exposes two ports: https for 443 and http for 80, as follows:
Name: my-service
Namespace: default
Subsets:
Addresses: 10.1.161.59
Ports:
Name Port Protocol
---- ---- --------
https 443 TCP
http 80 TCP
When you need to use the http port while intentionally bypassing the default https port (first one),
you must define DownstreamScheme to enable the provider to recognize the desired http port by comparing DownstreamScheme with the port name as follows:
"Routes": [
{
"ServiceName": "my-service",
"DownstreamScheme": "http", // port name -> http -> port is 80
}
]
Note: In the absence of a specified
DownstreamScheme(which is the default behavior), theKubeprovider will select the first available port from theEndpointSubsetV1.Portscollection. Consequently, if the port name is not designated, the default downstream scheme utilized will behttp.