Healthchecks (Terminus)
Terminus integration provides you with readiness/liveness health checks. Healthchecks are crucial when it comes to complex
backend setups. In a nutshell, a health check in the realm of web development usually consists of a special address, for example, https://my-website.com/health/readiness
.
A service or a component of your infrastructure (e.g., Kubernetes checks this address continuously. Depending on the HTTP status code returned from a GET
request to this address the service will take action when it receives an "unhealthy" response.
Since the definition of "healthy" or "unhealthy" varies with the type of service you provide, the Terminus integration supports you with a
set of health indicators.
As an example, if your web server uses MongoDB to store its data, it would be vital information whether MongoDB is still up and running.
In that case, you can make use of the MongooseHealthIndicator
. If configured correctly - more on that later - your health check address will return
a healthy or unhealthy HTTP status code, depending on whether MongoDB is running.
Getting started
To get started with @nestjs/terminus
we need to install the required dependency.
$ npm install --save @nestjs/terminus
Setting up a Healthcheck
A health check represents a summary of health indicators. A health indicator executes a check of a service, whether it is in a healthy or unhealthy state. A health check is positive if all the assigned health indicators are up and running. Because a lot of applications will need similar health indicators, @nestjs/terminus
provides a set of predefined indicators, such as:
HttpHealthIndicator
TypeOrmHealthIndicator
MongooseHealthIndicator
SequelizeHealthIndicator
MikroOrmHealthIndicator
PrismaHealthIndicator
MicroserviceHealthIndicator
GRPCHealthIndicator
MemoryHealthIndicator
DiskHealthIndicator
To get started with our first health check, let's create the HealthModule
and import the TerminusModule
into it in its imports array.
info Hint To create the module using the Nest CLI, simply execute the
$ nest g module health
command.
@@filename(health.module)
import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
@Module({
imports: [TerminusModule]
})
export class HealthModule {}
Our healthcheck(s) can be executed using a controller, which can be easily set up using the Nest CLI.
$ nest g controller health
info Info It is highly recommended to enable shutdown hooks in your application. Terminus integration makes use of this lifecycle event if enabled. Read more about shutdown hooks here.
HTTP Healthcheck
Once we have installed @nestjs/terminus
, imported our TerminusModule
and created a new controller, we are ready to create a health check.
The HTTPHealthIndicator
requires the @nestjs/axios
package so make sure to have it installed:
$ npm i --save @nestjs/axios axios