Kubernetes livenessProbe: testing container's health

2 min read

Every application will, eventually, fail. In order to detect that the container is failing and being able to recover this situation by restarting it we can use the livenessProbe.

To be able to configured a livenessProbe, we will have to configure it for each container we want to check. A livenessProbe that checks a HTTP port would look like follows:

apiVersion: v1
kind: Pod
metadata:
  name: demo-liveness
spec:
  containers:
  - name: liveness
    image: nginx
    livenessProbe:
      httpGet:
        path: /index.html
        port: 80
      initialDelaySeconds: 3
      periodSeconds: 3

In the configuration file, you can see that the Pod has a single Container. The periodSeconds field specifies that the kubelet should perform a liveness probe every 5 seconds. The initialDelaySeconds field tells the kubelet that it should wait 5 seconds before performing the first probe.

With the option, periodSeconds we are telling how much time we want to wait between probes (on the example 3 seconds). With the initialDelaySeconds we are telling how much time should it wait before performing the first probe. Starting Kubernetes v1.20 we have the startupProbe so we no longer have to take into account the amount of time it takes for starting the application

We can also configure a exec probe, using a command to run on the container instead of a HTTP probe, for example:

apiVersion: v1
kind: Pod
metadata:
  name: demo-liveness-exec
spec:
  containers:
  - name: liveness
    image: busybox
    args:
    - /bin/sh
    - -c
    - touch /tmp/healthy; sleep 60; rm -rf /tmp/healthy; sleep 300
    livenessProbe:
      exec:
        command:
        - cat
        - /tmp/healthy
      initialDelaySeconds: 3
      periodSeconds: 3

Posted on 23/08/2021