Skip to content

[.NET Core] Health check service with database

Thang Chung edited this page Jul 30, 2018 · 1 revision

2 methods to health check the SQL Server database

  1. Using command in yaml file
initContainers:
- name: init-mydb
  image: microsoft/mssql-server-linux:2017-latest
  env: 
  - name: "ACCEPT_EULA"
    value: "Y"
  - name: "MSSQL_SA_PASSWORD"
    value: "P@ssw0rd"
  command: ['sh', '-c', 'echo waiting for initDb; /opt/mssql-tools/bin/sqlcmd -S cart-db-service -U cs -P $MSSQL_SA_PASSWORD -l 1000 -Q "select getdate()"']

@thinhnotes is the orginal person to use this approach.

  1. Check in code like
  [Route("")]
  [ApiVersionNeutral]
  [ApiExplorerSettings(IgnoreApi = true)]
  public class HealthController : Controller
  {
    private IServiceProvider _serviceProvider;
    public HealthController(IServiceProvider serviceProvider)
    {
      _serviceProvider = serviceProvider;
    }

    [HttpGet("/healthz")]
    public ActionResult Get()
    {
      try
      {
        _serviceProvider.MigrateDbContext<InventoryDbContext>();
      }
      catch (Exception)
      {

        return new BadRequestResult();
      }
      
      return Ok();
    }
  }

We use the second approach to simplify the way we do a health check at the moment.