在您的应用程序中对kubernetes进行运行状况检查

Making your application more resilient with health checks

通过运行状况检查使您的应用程序更具弹性

Over the past year containerizing applications has become an extremely popular practice to quickly develop, ship and deploy applications. With the help of containerization tools like Docker, the desired container environment can be described in a declarative manner.

在过去的一年中,容器化应用程序已成为快速开发,运输和部署应用程序的一种非常流行的做法。 借助Docker等容器化工具,可以以声明方式描述所需的容器环境。

With Kubernetes, containerized applications can be deployed, scaled when needed, and further managed. Kubernetes has self-healing powers for containers — but only works to it’s fully potential when it’s set up right.

借助Kubernetes,可以部署,在需要时扩展和进一步管理容器化的应用程序。 Kubernetes具有容器的自我修复能力-但只有在正确设置后才能发挥其全部潜力。

In this article, we are going to implement health checks and corresponding probes so that Kubernetes is able to define whether a containerized application is healthy and can act accordingly.

在本文中,我们将实现运行状况检查和相应的探查,以便Kubernetes能够定义容器化应用程序是否健康并可以采取相应措施。

The implementation examples on the application side are implemented with .NET Core. The theory and implementations can be as well applied to Java/Spring Boot applications. Spring Boot offers the Actuator module to implement comparable functionality that is stated further into this article.

应用程序端的实现示例是使用.NET Core实现的。 该理论和实现也可以应用于Java / Spring Boot应用程序。 Spring Boot提供了 Actuator模块 来实现可比较的功能,本文将进一步介绍。

什么是Kubernetes探针? (What are Kubernetes probes?)

To understand what a probe in Kubernetes context is, it is smart to take a step back and look into what the definition of the word:

要了解Kubernetes上下文中的探针是什么,明智的做法是退后一步来查看单词的定义:

verb (used with object), probed, prob·ing.1. to search into or examine thoroughly; question closely:to probe one’s conscience.2. to examine or explore with a probe.verb (used without object), probed, prob·ing.3. to examine or explore with or as if with a probe.noun4. the act of probing.

动词(与宾语一起使用),探究,概率化。 1.彻底地搜寻或检查 仔细提问: 探究自己的良心。 2。 用探针进行检查或探索。 动词(不带宾语使用),探究,有问题。 3.用或好像用探针检查或探索。 名词 4.探测行为。

Definition by Dictionary

字典定义

With the help of the definition above, Kubernetes probes can be defined as an instrument to examine the state of a container. Kubernetes uses this probe functionality to determine if a container and thus the pod is unhealthy and if so, Kubernetes will use its self-healing power. Kubernetes will try to schedule replacement pods to get back to the desired amount of instances(replicas) of pods to get to a healthy state again.

借助以上定义,可以将Kubernetes探针定义为检查容器状态的工具。 Kubernetes使用此探针功能来确定容器(因此吊舱)是否不健康,如果是,Kubernetes将使用其自愈能力。 Kubernetes将尝试安排替换Pod以使其恢复到所需的Pod实例(副本)数量,以再次恢复健康状态。

Kubernetes uses probes during a rolling update to determine if the newly deployed pod is up. Only after reporting the new pod up, the old pod will be removed.

Kubernetes在滚动更新期间使用探针来确定新部署的Pod是否已启动。 仅在报告新的吊舱后,才会删除旧的吊舱。

Kubernetes has three types of probes that can be declared:

Kubernetes具有三种可以声明的探针:

  1. Liveness Probe: used to determine how alive the container is, regardless of dependencies. This probe is used to check whether the application that runs in the container, is not in an unresponsive state. An application could get into a deadlock state without being able to give any responses back.

    活动性探针 :用于确定容器的活动性,与依赖关系无关。 该探针用于检查在容器中运行的应用程序是否未处于无响应状态。 应用程序可能陷入死锁状态而无法返回任何响应。

  2. Readiness Probe: used to determine whether the container is ready to accept traffic. The container can enter a non-ready state when external dependencies are failing. For example: when connection to a database has not been successful, the container is determined as alive, but is not ready to accept traffic until the connection has been restored. Non-ready containers won’t be connected to load balancers by Kubernetes.

    Readiness Probe :用于确定容器是否准备好接受流量。 当外部依赖项失败时,容器可以进入非就绪状态。 例如:如果与数据库的连接未成功,则将容器确定为活动的,但直到恢复连接后,容器才准备好接受流量。 未就绪的容器不会通过Kubernetes连接到负载均衡器。

  3. Startup Probe: used to determine if the container started up. When configured, liveness and readiness probes are disabled until proper startup. This is to avoid slow-starting containers being killed before properly started up. This probe is available since K8S version 1.16 and in Alpha state.

    启动探针 :用于确定容器是否已启动。 配置后,活动和就绪探针将被禁用,直到正确启动为止。 这是为了避免缓慢启动的容器在正常启动之前被杀死。 从K8S版本1.16开始,此探针可用,并且处于Alpha状态。

Configuring probes is simple. The configuration is part of the Pod specification and thus can be defined in a deployment or in a stateful set. The liveness, readiness and startup probes are configured similar. The difference is that the key is different for each node. livenessProbe, readinessProbe and startupProbe respectively.

配置探针很简单。 该配置是Pod规范的一部分,因此可以在部署中或有状态集合中进行定义。 活动,就绪和启动探针的配置类似。 区别在于每个节点的密钥都不相同。 livenessProbereadinessProbestartupProbe分别。

apiVersion: v1
kind: Pod
metadata:
  name: pod-with-healthcheck
spec:
  containers:
  - name: liveness
    image: k8s.gcr.io/liveness
    args:
    - /server
    livenessProbe:
      httpGet:
        path: /health
        port: 8080
      initialDelaySeconds: 3
      periodSeconds: 3

It’s the Kubelet that makes use of these probes to check whether the container is behaving as expected. The Kubelet is the server agent that runs on each node for managing the node and is responsible for starting scheduled pods and containers.

使用这些探针的正是Kubelet ,以检查容器的行为是否符合预期。 Kubelet是在每个节点上运行的服务器代理,用于管理该节点,并负责启动调度的Pod和容器。

The probing is done by sending requests to the defined probe endpoints. The Kubelet is able to send either HTTP or TCP requests as probes, on a set interval to the container. On the basis of the response the container is defined as healthy or unhealthy.

通过将请求发送到已定义的探测端点来完成探测。 Kubelet能够按设定的时间间隔将HTTP或TCP请求作为探针发送到容器。 根据响应,将容器定义为健康或不健康。

In the examples that will follow, the configuration of the probes will be explained in depth.

在下面的示例中,将对探针的配置进行深入说明。

什么是健康检查? (What are health checks?)

As explained before, with the help of probe endpoints, Kubernetes can determine whether the application is running in a healthy state. But how can we detect that a running application is in an unhealthy state and not being able to accept traffic?

如前所述,借助探测端点,Kubernetes可以确定应用程序是否以健康状态运行。 但是,我们如何检测正在运行的应用程序处于不正常状态并且不能接受流量呢?

By implementing an health checks API inside our application! With a health checks API, an endpoint is exposed that returns a success response on healthy state, such as an HTTP 200 status code. If any health check fails, it returns an unhealthy response, like an HTTP 503 status code.

通过在我们的应用程序内部实现运行状况检查API ! 使用运行状况检查API,可以公开一个端点,该端点将在运行状况良好的情况下返回成功响应,例如HTTP 200状态代码。 如果任何运行状况检查失败,它将返回不正常的响应,例如HTTP 503状态代码。

Implementing health checks can be done in two ways:

可以通过两种方式来执行健康检查:

  • Shallow health checks: From the application perspective, only returning a healthy response when the endpoint is invoked. In this case, no extra checks are done on external dependencies, comparable to the liveness probe of Kubernetes. It will simply tell that the application is live, but won’t tell anything whether requests will fail due to failing dependencies.

    浅层健康检查:从应用程序的角度来看,仅在调用端点时返回健康响应。 在这种情况下,与Kubernetes的活动性调查相比,无需对外部依赖项进行额外检查。 它只会告诉应用程序处于活动状态,但不会告诉您请求是否由于依赖关系失败而失败。

  • Deep health checks: returns the actual state of dependencies. In this case, extra checks are done whether the connections on external dependencies are in a healthy state. This is comparable to the readiness probe of Kubernetes. These checks can be done by actually executing a request against the dependency. For example running a query against a database.

    深度健康检查:返回依赖项的实际状态。 在这种情况下,将额外检查外部依赖项上的连接是否处于正常状态。 这可与Kubernetes的就绪性调查相媲美。 这些检查可以通过实际对依赖项执行请求来完成。 例如,对数据库运行查询。

Determining how much deep health checks are needed and how they are implemented depends per individual case. Simply checking whether a connection is still open could be enough in one situation. Integrating checks whether the interaction can be done could be more appropriate on other situations. Important is to find the right balance. Expensive checks, like running heavy queries, should be avoided since this slows down the response and can create stability issues.

确定需要多少深度健康检查以及如何进行深度检查取决于每个案例。 在一种情况下,仅检查连接是否仍处于打开状态就足够了。 集成检查是否可以进行交互可能更适合其他情况。 重要的是要找到合适的平衡。 应避免进行昂贵的检查,例如运行繁重的查询,因为这会减慢响应速度并可能导致稳定性问题。

在ASP.NET Core中构建运行状况检查终结点 (Building Health Check endpoints in ASP.NET Core)

Okay, we understand now the basics of how Kubernetes checks the health state of a pod and determines if its containers are up and ready for accepting traffic. We understand now what health checks are. But how can we implement logic inside an ASP.NET Core application that actually reports whether the running application is healthy or not?

好的,我们现在了解Kubernetes如何检查Pod的健康状态并确定其容器是否已打开并准备接受流量的基础知识。 我们现在了解什么是健康检查。 但是,我们如何在ASP.NET Core应用程序中实现实际报告正在运行的应用程序是否正常的逻辑呢?

Microsoft developed for this the health checks functionality. With a base package a health check service can be set up. With flexible configuration for customizable health endpoints and a base interface, health checks for external dependencies like databases can be created in the application. These endpoints can then be requested by Kubernetes.

Microsoft为此开发运行状况检查功能。 使用基本软件包,可以设置健康检查服务。 通过针对可自定义的运行状况终结点和基本接口的灵活配置,可以在应用程序中创建外部依赖项(如数据库)的运行状况检查。 然后,Kubernetes可以请求这些端点。

In the .NET community members created several ready to use NuGet packages to implement quick health checks for external dependencies. The source of these health check packages can be found in a large GitHub repository. Since they are setup for general usage, they can be used as a reference to customize them according desired needs.

在.NET社区中,成员创建了几个随时可以使用的NuGet包,以实现对外部依赖项的快速健康检查。 这些健康检查包的来源可以在大型GitHub存储库中找到 。 由于它们是为一般用途而设置的,因此它们可以用作参考,以根据所需需求对其进行自定义。

案件 (Case)

Let’s assume that we have an ASP.NET Core web application with a dependency on a Mongo Database. The application saves and retrieves information. This makes the application unhealthy when the database connection is interrupted. This is due to the fact that data is not accessible. This results in a situation where interaction with the application is not possible.

假设我们有一个依赖于Mongo数据库的ASP.NET Core Web应用程序。 该应用程序保存并检索信息。 当数据库连接中断时,这会使应用程序不正常。 这是因为无法访问数据。 这导致无法与应用程序进行交互的情况。

For the health check, a custom implementation will be made. This to show the possibilities to extend the health check with customized checks.

对于健康检查,将进行自定义实现。 这显示了使用自定义检查扩展健康检查的可能性。

A boiler plate ASP.NET MVC project can be created to follow the walkthrough. Since this implementation is focusing around health checks, aditional logic for interaction with the database won’t be implemented.

可以创建一个样板ASP.NET MVC项目来遵循本演练。 由于此实现的重点是运行状况检查,因此不会实现与数据库交互的附加逻辑。

Containerization of the application is out of scope for this tutorial. A good tutorial to containerize a .NET Core Application can be found here. The corresponding Kubernetes deployment haven’t been created yet and will be created during the setup of the probes.

应用程序的容器化超出了本教程的范围。 在这里可以找到有关容器化.NET Core应用程序的很好的教程。 尚未创建相应的Kubernetes部署,并将在探针设置期间创建它。

实作 (Implementation)

Let’s open the IDE and create a new solution with a new project using the ASP.NET Core MVC template. For this walkthrough the name HealthChecks.DemoApplication will be used.

让我们打开IDE并使用ASP.NET Core MVC模板通过新项目创建新的解决方案。 在本演练中,将使用名称HealthChecks.DemoApplication

The used template creates a boilerplate code for the Startup class. Like with multiple packages for ASP.NET Core, extension methods can be added in this class to (1) register dependencies for the Dependency Injection framework and (2) to register middleware to the request pipeline.

使用的模板为Startup类创建样板代码。 与ASP.NET Core的多个程序包一样,可以在此类中添加扩展方法,以(1)注册依赖关系注入框架的依赖关系,以及(2)将中间件注册到请求管道。

To be able to create the MongoDB health check and expose them by their respected endpoints, two NuGet packages should be added to the project:

为了能够创建MongoDB运行状况检查并通过其受尊重的端点公开它们,应在项目中添加两个NuGet软件包:

  1. The Microsoft.Extensions.Diagnostics.HealthChecks package offers the functionality for the health checks framework. This package is responsible for implementing the endpoints and the health check service.

    Microsoft.Extensions.Diagnostics.HealthChecks包提供了运行状况检查框架的功能。 该软件包负责实现端点和运行状况检查服务。

  2. The MongoDB.Driver package offers the client API to be able to interact with a MongoDB database.

    MongoDB.Driver软件包提供了客户端API,以便能够与MongoDB数据库进行交互。

实施健康检查逻辑 (Implementing the health check logic)

Let’s implement the health check first. A health check is created by creating a class that implements the IHealthCheck interface. This interface has a CheckHealthAsync method defined that runs the health check and reports the result of the health check by returning a HealthCheckResult object. With the help of a HealthCheckContext argument, specific information of the health check can be requested. At last the method as well specifies a CancellationToken argument, this to the fact that the method invocation is asynchronous and can allows cancellation by other threads.

让我们先执行健康检查。 通过创建实现IHealthCheck接口的类来创建运行状况检查。 此接口具有定义的CheckHealthAsync方法,该方法运行运行状况检查并通过返回HealthCheckResult对象来报告运行状况检查的结果。 借助于HealthCheckContext参数,可以请求运行状况检查的特定信息。 最后,该方法还指定了CancellationToken参数,这是因为方法调用是异步的,并且可以允许其他线程取消。

summarized, the signature of the method is as following:

总结一下,该方法的签名如下:

Task<HealthCheckResult> IHealthCheck.CheckHealthAsync(HealthCheckContext, CancellationToken)

Create inside the demo application a new folder called HealthChecks and inside this folder create a MongoDbHealthCheck class. Your folder structure should be matching to the following structure:

在演示应用程序中创建一个名为HealthChecks的新文件夹,并在此文件夹中创建MongoDbHealthCheck类。 您的文件夹结构应与以下结构匹配:

Image for post
Folder structure demonstration application
文件夹结构演示应用

Inside the created class, with the help of this reference code, add the following code to implement the full health check implementation:

在创建的类中,借助此参考代码 ,添加以下代码以实现完整的运行状况检查实现:

using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using MongoDB.Driver;


namespace HealthChecks.DemoApplication.HealthChecks
{
    public class MongoDbHealthCheck
        : IHealthCheck
    {
        private static readonly ConcurrentDictionary<MongoClientSettings, MongoClient> _mongoClient = new ConcurrentDictionary<MongoClientSettings, MongoClient>();
        private readonly MongoClientSettings _mongoClientSettings;
        private readonly string _specifiedDatabase;


        public MongoDbHealthCheck(string connectionString)
        {
            var mongoDbUrl = MongoUrl.Create(connectionString);


            _specifiedDatabase = mongoDbUrl.DatabaseName;
            _mongoClientSettings = MongoClientSettings.FromUrl(mongoDbUrl);
        }


        public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                var mongoClient = _mongoClient.GetOrAdd(_mongoClientSettings, settings => new MongoClient(settings));


                if (!string.IsNullOrEmpty(_specifiedDatabase))
                {
                    using var cursor = await mongoClient
                        .GetDatabase(_specifiedDatabase)
                        .ListCollectionNamesAsync(cancellationToken: cancellationToken);


                    await cursor.FirstAsync(cancellationToken);
                }
                else
                {
                    using var cursor = await mongoClient.ListDatabaseNamesAsync(cancellationToken);
                    await cursor.FirstOrDefaultAsync(cancellationToken);
                }


                return HealthCheckResult.Healthy();
            }
            catch (Exception ex)
            {
                return new HealthCheckResult(context.Registration.FailureStatus, exception: ex);
            }
        }
    }
}

At lines 13–23, the needed private properties are defined. These properties are initialized by the constructor of the health check. The constructor accepts the MongoDB connection string that will be used to connect with the database to check the health. Inside the connection string, a database name can be defined. The constructor can be either invoked through Dependency injection or used directly. For simplicity, the latter is used.

在第13-23行,定义了所需的私有属性。 这些属性由运行状况检查的构造函数初始化。 构造函数接受MongoDB连接字符串,该字符串将用于与数据库连接以检查运行状况。 在连接字符串中,可以定义数据库名称。 构造函数可以通过依赖注入来调用,也可以直接使用。 为了简单起见,使用后者。

At lines 25–51, the actual health check logic is implemented. Depending on whether the specified connection string contains a database name, the check will either try to retrieve all collections in the specified database, or try to retrieve all the database names. If the check is successful, a succesful response is returned. This can be done by returning the return value of the Healthy method on the HealthCheckResult class, used on line 45. If by any means an exception is thrown, the health check should fail and return a failed response. This is done on line 49. Inside the result, the exception is added for verbosity.

在第25-51行,实现了实际的健康检查逻辑。 根据指定的连接字符串是否包含数据库名称,检查将尝试检索指定数据库中的所有集合,或者尝试检索所有数据库名称。 如果检查成功,则返回成功响应。 这可以通过在第45行上使用的HealthCheckResult类上返回Healthy方法的返回值来完成。如果以任何方式抛出异常,则运行状况检查将失败并返回失败的响应。 这是在第49行上完成的。在结果内部,为详细程度添加了例外。

As explained earlier, this implementation is done with room for customization in mind. The implementation can be adjusted according your desired needs.

如前所述,此实现是在考虑自定义空间的情况下完成的。 可以根据您的需要调整实现。

注册健康检查服务和健康检查 (Register the health check service and the health check)

After implementing the health check itself, the health check needs to be registered to the health checks service.

实施健康检查本身后,需要将健康检查注册到健康检查服务。

Adding the health checks service is done by using the AddHealthChecks extension method inside the ConfigureServices(IServiceCollection services) method of the Startup class. This method registers the health checks service in the DI container and returns a IHealthChecksBuilder instance which can be used to register the earlier implemented health check.

通过使用Startup类的ConfigureServices(IServiceCollection services)方法内的AddHealthChecks扩展方法来完成运行状况检查服务的添加。 此方法在DI容器中注册运行状况检查服务,并返回IHealthChecksBuilder实例,该实例可用于注册较早实施的运行状况检查。

The IHealthChecksBuilder offers the AddCheck method and its overloads to register the health checks. As told before, the health checks can be either registered by dependency injection or directly. Both methods are shown in the snippet below.

IHealthChecksBuilder提供AddCheck方法及其重载来注册运行状况检查。 如前所述,可以通过依赖注入或直接注册运行状况检查。 两种方法都显示在下面的代码段中。

services.AddHealthChecks()
    .AddCheck<MongoDbHealthCheck>(
        "Dependency_Injection_health_check",
        failureStatus: HealthStatus.Unhealthy,
        tags: new[] { "ready" })
    .AddCheck(
        "Direct_health_check",
        new MongoDbHealthCheck("mongodb://localhost:27017/"),
        failureStatus: HealthStatus.Unhealthy,
        tags: new[] { "ready" });

In the overload, the first argument resembles the name of the health check. The overload accepts as a failureStatus property to be set, which describes the actual status that needs to be returned when the health check fails. The options are Healthy, Degraded and Unhealthy (default).

在重载中,第一个参数类似于运行状况检查的名称。 重载接受要设置的failureStatus属性,该属性描述运行状况检查失败时需要返回的实际状态。 选项为“健康”,“降级”和“不健康”(默认)。

Tags can be added to health checks by populating the tags property with an array of strings. These tags can be used during the endpoint registrations to include/exclude specific health checks.

通过使用字符串数组填充tags属性,可以将标签添加到运行状况检查。 这些标记可在端点注册期间使用,以包括/排除特定的运行状况检查。

While the AddHealthChecks method itself is idempodent, meaning multiple invocations of the method would only one instance of the service, the AddCheck method is not. When the two methods above are both invoked, two instances will be added to the health check service.

尽管AddHealthChecks方法本身是确定的,这意味着对该方法的多次调用将仅是该服务的一个实例,而AddCheck方法则不是。 当同时调用上述两种方法时,两个实例将添加到运行状况检查服务。

For the scope of the demo the direct registration will be enough. For production implementation, configuration by using Configuration Providers would be highly suggested.

对于演示的范围,直接注册就足够了。 对于生产实施,强烈建议使用配置提供程序进行配置

The resulting ConfigureServices method should be matching to:

产生的ConfigureServices方法应与以下各项匹配:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHealthChecks()
        .AddCheck(
            "MongoDb",
            new MongoDbHealthCheck("mongodb://localhost:27017/"),
            failureStatus: HealthStatus.Unhealthy,
            tags: new[] { "ready" });
}

实施健康检查端点 (Implementing the health checks endpoints)

Setting up the health checks endpoints is the last step that has to be done in our application.

设置运行状况检查端点是我们应用程序中必须完成的最后一步。

Since two different endpoints are needed for the Kubernetes liveness and readiness probes, two separate endpoints will be added. a health checks endpoint is added to the pipeline by calling the MapHealthChecks method inside the endpoints section of the Startup.Configure method. The snippet below resembles the two endpoints:

由于Kubernetes活跃性和就绪性探测需要两个不同的端点,因此将添加两个单独的端点。 通过在Startup.Configure方法的端点部分内调用MapHealthChecks方法,将运行状况检查端点添加到管道中。 下面的代码段类似于两个端点:

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health/ready", new HealthCheckOptions()
    {
        Predicate = (check) => check.Tags.Contains("ready"),
    });


    endpoints.MapHealthChecks("/health/live", new HealthCheckOptions()
    {
        Predicate = (_) => false
    });
});

The first argument for the MapHealthChecks accepts the path, relative of where the application runs, where the health status can be retrieved.

MapHealthChecks的第一个参数接受相对于应用程序运行位置的路径,该路径可以检索健康状态。

The second argument accepts an instance of HealthCheckOptions. Inside this options class, a Predicate function can set, to filter on specific tagged health checks. In the case of the live probe, only giving a success would suffice. For the readiness probe the external dependency needs to be checked. Since the previously implemented MongoDB health check is tagged with “ready”, a predicate is added here. This makes sure that only the health checks tagged with this tag are checked.

第二个参数接受HealthCheckOptions的实例。 在此选项类内,可以设置Predicate函数以过滤特定的带标签的运行状况检查。 对于实时探测,仅给出成功就足够了。 对于准备情况探针,需要检查外部依赖关系。 由于先前实施的MongoDB健康检查标记为“就绪”,因此在此处添加了谓词。 这样可以确保仅检查带有此标签的健康检查。

测试健康检查端点 (Testing the health check endpoints)

When starting the application in debug mode, and navigating to “/health/live”, our application returns the healthy state.

在调试模式下启动应用程序并导航至“ / health / live”时,我们的应用程序将返回正常状态。

When navigating to “/health/ready”, the application will return an Unhealthy response with the 503 http status code. With the help of Docker, an instance of MongoDB can be quickly started. This can be done executing the following command in the terminal:

当导航到“ / health / ready”时,该应用程序将返回带有503 http状态代码的不正常响应。 借助Docker,可以快速启动MongoDB实例。 可以在终端中执行以下命令来完成此操作:

docker run -p 27017:27017 -d mongo:latest

docker run -p 27017:27017 -d mongo:latest

When refreshing the the “/health/ready” endpoint, the response should now be as well “Healthy”. Congratulations, the endpoints have been implemented successfully in our application.

刷新“ / health / ready”端点时,响应现在也应该为“ Healthy”。 恭喜,端点已在我们的应用程序中成功实现。

在Kubernetes中实施活跃性和准备情况调查 (Implementing the liveness and readiness probes in Kubernetes)

Last but not least, the probes need to be added and configured in the Kubernetes resource for this application. Since building and deploying the image to a registry is out of scope for this walkthrough, the assumption is made that the image is already available on the specific nodes. The application runs on port 80 inside the container.

最后但并非最不重要的一点是,需要为此应用程序在Kubernetes资源中添加和配置探针。 由于构建映像并将其部署到注册表不在本演练范围之内,因此,假定映像已在特定节点上可用。 该应用程序在容器内部的端口80上运行。

The Kubernetes deployment resource for this application will look as follows:

该应用程序的Kubernetes部署资源如下所示:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: demoapplication
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: demoapplication
  template:
    metadata:
      labels:
        app.kubernetes.io/name: demoapplication
    spec:
      containers:
        - name: demoapplication
          image: demoapplication:latest
          ports:
            - name: http
              containerPort: 80
              protocol: TCP
          livenessProbe:
            httpGet:
              path: /health/live
              port: http
            initialDelaySeconds: 10
            failureThreshold: 3
            periodSeconds: 10
          readinessProbe:
            httpGet:
              path: /health/ready
              port: http
            initialDelaySeconds: 10
            failureThreshold: 3
            periodSeconds: 30

Inside the container specification the port 80 has been named as http. The liveness probe and readiness probe can connect to this port by using the name directly. The following properties can be configured per probe:

在容器规范内,端口80已命名为http。 活动探针和就绪探针可以直接使用名称连接到此端口。 可以为每个探针配置以下属性:

  • With the initialDelaySeconds property, a delay in seconds can be set before Kubernetes starts probing. Defaults to 0.

    使用initialDelaySeconds属性,可以在Kubernetes开始探测之前设置以秒为单位的延迟。 预设为0。

  • With the failureTreshold property, the amount of retries can be set before Kubernetes (1) in case of the liveness probe restarts the container, or (2) in case of the readiness probe determines the container as unhealthy. Defaults to 3.

    使用failureTreshold属性,可以在Kubernetes之前设置重试次数(1)(如果活动性探针重新启动容器,或者(2)如果就绪性探针确定容器不健康)。 默认为3。

  • With a successThreshold property, an amount of minimum consecutive successful probes can be set before the container can be determined healthy, after being in a failed state before. Must be 1 for Liveness probes, defaults to 1.

    使用successThreshold属性,可以设置一定数量的最小连续成功探测,然后才能确定容器是否处于健康状态,之后才处于失败状态。 对于“活力”探针,必须为1,默认为1。

  • With a periodSeconds property, the period between probes can be set. Defaults to 10 seconds.

    使用periodSeconds属性,可以设置periodSeconds之间的时间间隔。 默认为10秒。

摘要 (Summary)

Kubernetes uses three types of probes to determine whether an application is healthy or not. These probes are respectively liveness, readiness and startup probes.

Kubernetes使用三种类型的探针来确定应用程序是否正常。 这些探针分别是活动性,就绪性和启动性探针。

With exposing health checks endpoints in an application, Kubernetes can use these endpoints to probe the health of the application. Health checks can be shallow or deep. With shallow health checks only the liveness of the application is tested. With deep health checks additional external dependencies of the application can be tested.

通过公开应用程序中的运行状况检查端点,Kubernetes可以使用这些端点来探测应用程序的运行状况。 健康检查可以很浅也可以很深。 使用浅层运行状况检查仅测试应用程序的活动性。 通过深度健康检查,可以测试应用程序的其他外部依赖关系。

An implementation of two health checks endpoints has been made in an ASP.NET Core application. This is done by using the Health Checks package. With this package, a MongoDB health check has been implemented.

在ASP.NET Core应用程序中实现了两个运行状况检查终结点的实现。 这是通过使用运行状况检查程序包完成的。 使用此软件包,已实现了MongoDB运行状况检查。

Inside a Kubernetes deployment resource, two probes have been added to make the containerized application more resilient.

在Kubernetes部署资源内部,添加了两个探针以使容器化应用程序更具弹性。

翻译自: https://medium.com/swlh/implement-health-checks-for-kubernetes-in-your-application-951eb483a05c

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值