Fix API deploy healthcheck by starting Kestrel before migrate/seed.
CI / backend (push) Canceled after 0s
CI / frontend (push) Canceled after 0s

Compose was marking the API unhealthy because bootstrap blocked app.Run(), so /health/live never answered within the HEALTHCHECK window.
This commit is contained in:
2026-10-04 19:27:21 +08:00
parent d013dd4bb5
commit 7d7332641f
9 changed files with 915 additions and 22 deletions
@@ -0,0 +1,62 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Minio;
using Minio.DataModel.Args;
/// <summary>
/// Runs migrate / demo seed / MinIO bucket ensure after Kestrel is listening.
/// Keeping this off the Program.cs path before <c>app.Run()</c> lets Docker's
/// /health/live HEALTHCHECK succeed while dependencies warm up; /health/ready
/// stays gated by <see cref="StartupHealthCheck"/> until this finishes.
/// </summary>
public sealed class AppBootstrapHostedService : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly StartupHealthCheck _startupHealthCheck;
private readonly IHostApplicationLifetime _lifetime;
private readonly ILogger<AppBootstrapHostedService> _logger;
public AppBootstrapHostedService(
IServiceScopeFactory scopeFactory,
StartupHealthCheck startupHealthCheck,
IHostApplicationLifetime lifetime,
ILogger<AppBootstrapHostedService> logger)
{
_scopeFactory = scopeFactory;
_startupHealthCheck = startupHealthCheck;
_lifetime = lifetime;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Yield so the generic host can finish starting Kestrel before we block on I/O.
await Task.Yield();
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.MigrateAsync(stoppingToken);
await DataSeeder.SeedAsync(db);
var minio = scope.ServiceProvider.GetRequiredService<IMinioClient>();
var minioOpts = scope.ServiceProvider.GetRequiredService<IOptions<MinioOptions>>().Value;
if (!await minio.BucketExistsAsync(
new BucketExistsArgs().WithBucket(minioOpts.BucketName), stoppingToken))
{
await minio.MakeBucketAsync(
new MakeBucketArgs().WithBucket(minioOpts.BucketName), stoppingToken);
_logger.LogInformation("Created MinIO bucket {Bucket}", minioOpts.BucketName);
}
_startupHealthCheck.StartupCompleted = true;
_logger.LogInformation("Application bootstrap completed.");
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogCritical(ex, "Application bootstrap failed — stopping host.");
_lifetime.StopApplication();
}
}
}
+3 -1
View File
@@ -52,7 +52,9 @@ USER app
ENV ASPNETCORE_URLS=http://+:8080
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
# Liveness only (/health/live). Readiness is asserted by CD smoke (/health/ready).
# start-period covers process + Kestrel bind; migrate/seed no longer block listen.
HEALTHCHECK --interval=10s --timeout=5s --start-period=40s --retries=6 \
CMD curl -fsS http://localhost:8080/health/live || exit 1
ENTRYPOINT ["dotnet", "VigilCareRecordsAPI.dll"]
@@ -0,0 +1,25 @@
using Microsoft.Extensions.Diagnostics.HealthChecks;
/// <summary>
/// Tracks whether one-shot startup work (migrate / seed / MinIO bucket) has finished.
/// Tagged on /health/ready and /health/startup so probes stay unhealthy until bootstrap completes.
/// </summary>
public sealed class StartupHealthCheck : IHealthCheck
{
private volatile bool _completed;
public bool StartupCompleted
{
get => _completed;
set => _completed = value;
}
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context, CancellationToken cancellationToken = default)
{
return Task.FromResult(
_completed
? HealthCheckResult.Healthy("Startup completed.")
: HealthCheckResult.Unhealthy("Startup still running."));
}
}
+13 -17
View File
@@ -6,10 +6,8 @@ using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Minio;
using Minio.DataModel.Args;
using Prometheus;
using Serilog;
using StackExchange.Redis;
@@ -148,8 +146,10 @@ try
builder.Services.AddHostedService<MetricsCollectorService>();
builder.Services.AddHostedService<PromotionRetryService>();
// Health checks
builder.Services.AddHealthChecks()
// Health checks. Startup bootstrap (migrate/seed/MinIO) runs in a hosted
// service AFTER Kestrel listens so Docker's /health/live probe can pass;
// /health/ready stays gated until StartupHealthCheck flips.
var healthChecks = builder.Services.AddHealthChecks()
.AddNpgSql(
builder.Configuration.GetConnectionString("DefaultConnection")!,
name: "postgresql",
@@ -162,6 +162,15 @@ try
"minio",
tags: new[] { "ready" });
if (!isTesting)
{
builder.Services.AddSingleton<StartupHealthCheck>();
builder.Services.AddHostedService<AppBootstrapHostedService>();
healthChecks.AddCheck<StartupHealthCheck>(
"startup",
tags: new[] { "ready", "startup" });
}
builder.Services.AddValidatorsFromAssemblyContaining<Program>();
builder.Services.AddScoped<ValidationFilter>();
builder.Services.AddControllers(options =>
@@ -229,19 +238,6 @@ try
}
});
if (!app.Environment.IsEnvironment("Testing"))
{
using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.MigrateAsync();
await DataSeeder.SeedAsync(db);
var minio = scope.ServiceProvider.GetRequiredService<IMinioClient>();
var minioOpts = scope.ServiceProvider.GetRequiredService<IOptions<MinioOptions>>().Value;
if (!await minio.BucketExistsAsync(new BucketExistsArgs().WithBucket(minioOpts.BucketName)))
await minio.MakeBucketAsync(new MakeBucketArgs().WithBucket(minioOpts.BucketName));
}
app.Run();
}
catch (System.Exception)