Kubernetes-查找服务中有多少个副本? [英] Kubernetes - Finding out how many replicas there are in a service?
问题描述
我在一个服务中分组了一个.net核心C#控制台应用程序的多个副本.我希望能够在每个副本中读取它们的总数(在重新缩放比例之后->总数减少或增加).
I have multiple replicas of a .net core C# console application grouped in a service. I would like to be able to be read inside each of the replicas the total number of them (after they get rescaled -> total number decreases or increases).
推荐答案
您需要查询kubernetes api服务器以从Pod中运行的应用程序获取副本的详细信息.
You need to query kubernetes api server to get the details of replicas from your application running inside a pod.
使用Kubernetes API服务器进行身份验证:
要查询已启用RBAC的kubernetes api服务器,您需要进行身份验证,并且根据要查询的api端点,还需要必需的角色.
To query kubernetes api server which has RBAC enabled, you need to be authenticated and depending on the api endpoint that you are querying you also need required roles.
每个Pod都有一个与之关联的服务帐户,您可以使用该服务帐户向api服务器进行身份验证.您需要创建以下资源:
Every pod has a service account associated with it using which you can authenticate with the api-server. You need to create the following resources:
-
ServiceAccount
并将其与窗格关联.您还可以使用默认的服务帐户,但是最好创建新的服务帐户,这样就不必将额外的角色授予命名空间中的所有Pod. -
Role
具有get
部署副本数 的特权
-
RoleBinding
将Role
绑定到ServiceAccount
.
ServiceAccount
and associate it with the pod. You can also use the default service account but it is better to create new service account so that you don't grant the extra roles to all the pods in the namespace.Role
which has privileges toget
the number of replicas of deploymentRoleBinding
to bind theRole
toServiceAccount
.
注意:根据您要查询的资源类型,您可能需要ClusterRole
和ClusterRoleBinding
而不是Role
和RoleBinding
.
Note: Depending on the type of resource you are trying to query, you might need ClusterRole
and ClusterRoleBinding
instead of Role
and RoleBinding
.
要将ServiceAccount与Pod关联,请使用Pod规范中的spec.serviceAccountName
字段.
To associate the ServiceAccount with the pod, use spec.serviceAccountName
field in the pod spec.
Kubernetes将与服务帐户关联的令牌安装在/var/run/secrets/kubernetes.io/serviceaccount/token
的每个窗格中.
Kubernetes mounts the token associated with the service account inside every pod at /var/run/secrets/kubernetes.io/serviceaccount/token
.
查询Kubernetes API服务器:
-
您可以在应用程序的docker映像中安装
kubectl
,然后从代码中调用它以查询api服务器.kubectl
可以检测到它正在从Pod内部运行,并自动使用令牌来通过kubernetes api-server进行身份验证.
You can install
kubectl
inside your application's docker image and call it from your code to query the api-server.kubectl
can detect that it is being run from inside a pod and use the token automatically to authenticate with kubernetes api-server.
您还可以使用kubernetes客户端库( https://github.com/kubernetes -client/csharp ).在这种情况下,您需要使用InClusterConfig
来使用服务帐户令牌.
You can also use a kubernetes client library(https://github.com/kubernetes-client/csharp). In this case, you need to use InClusterConfig
to use the service account token.
var config = KubernetesClientConfiguration.InClusterConfig()
var client = new Kubernetes(config);
这篇关于Kubernetes-查找服务中有多少个副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!