Kubernetes healthcheck without API endpoint

1 minute read

Let’s say you’re running an API-less service: an application which does not expose any endpoints. A background service which is handling queues, scheduled tasks, etc. How to ensure that container of this service is alive? Solution consists of two parts.

1. Service signals that it is running

There’re multiple ways to do it but the simplest one - to write something to a file. For example, each time reading a message from the queue the service can write current timestamp like this (C#):

1
await File.WriteAllTextAsync(".health", DateTime.UtcNow.ToString("s"));
The content of the file is not so important but the fact that the file system was updated is.

2. Liveness probe checks the file

The k8s exec liveness probe:

1
2
3
4
5
6
7
livenessProbe:
  exec:
    command:
    - .healthcheck.sh
  initialDelaySeconds: 30
  timeoutSeconds: 30
  periodSeconds: 30

And the corresponding healthcheck.sh:

1
find .health -newermt '-30 seconds' | grep .

Which means that if application does not update .health file every 30 seconds - it is considered as unhealthy and will be restarted by orchestrator.

In order to use find command with -newermt option in Alpine Linux, findutils package should be installed: apk add findutils.