How can I implement health checks in a .NET Core Worker Service?
The service will be run inside Docker and needs to be able to check the health of the service.
Register health check services with AddHealthChecks in Startup. ConfigureServices . Create a health check endpoint by calling MapHealthChecks in Startup. Configure .
To monitor the availability of your microservices, orchestrators like Kubernetes and Service Fabric periodically perform health checks by sending requests to test the microservices. When an orchestrator determines that a service/container is unhealthy, it stops routing requests to that instance.
When developing ASP.NET Core Microservices, you can use a built-in health monitoring feature by using a nuget package Microsoft. Extension. Diagnostic. HealthCheck.
Another way of doing this is to implement IHealthCheckPublisher
.
The benefits of this approach is the ability to re-use your existing IHealthCheck
s or integration with 3rd party libraries that rely on IHealthCheck
interface (like this one).
Though you still target Microsoft.NET.Sdk.Web
as the SDK you don't need to add any asp.net specifics.
Here is an example:
public static IHostBuilder CreateHostBuilder(string[] args) { return Host .CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { services .AddHealthChecks() .AddCheck<RedisHealthCheck>("redis_health_check") .AddCheck<RfaHealthCheck>("rfa_health_check"); services.AddSingleton<IHealthCheckPublisher, HealthCheckPublisher>(); services.Configure<HealthCheckPublisherOptions>(options => { options.Delay = TimeSpan.FromSeconds(5); options.Period = TimeSpan.FromSeconds(5); }); }); } public class HealthCheckPublisher : IHealthCheckPublisher { private readonly string _fileName; private HealthStatus _prevStatus = HealthStatus.Unhealthy; public HealthCheckPublisher() { _fileName = Environment.GetEnvironmentVariable(EnvVariableNames.DOCKER_HEALTHCHECK_FILEPATH) ?? Path.GetTempFileName(); } public Task PublishAsync(HealthReport report, CancellationToken cancellationToken) { // AWS will check if the file exists inside of the container with the command // test -f $DOCKER_HEALTH_CHECK_FILEPATH var fileExists = _prevStatus == HealthStatus.Healthy; if (report.Status == HealthStatus.Healthy) { if (!fileExists) { using var _ = File.Create(_fileName); } } else if (fileExists) { File.Delete(_fileName); } _prevStatus = report.Status; return Task.CompletedTask; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With