What is a liveness probe?
Liveness probes are used by the kubelet (kubernetes agent) to identify when to restart a container. The kubelet can identify a pod crash and restart the pod in such an event. However, at times, it may happen that the pod is alive but the application is in a state where it cannot serve requests, and restarting the application makes sense.
For example, your application might have gone into a deadlock, and a restart may allow it to recover and start serving the requests again.
How to configure a liveness probe?
Liveness is configured in a pod container spec. You can see an example below.
In the code snippet above, the pod has a single container. Letās look at what each line does in some detail.
- Line 15Ā defines the liveness probe. We are using theĀ
execĀ to indicate that the liveness probe is a command. - Line 18Ā andĀ 19Ā indicate that the liveness probe will do aĀ
cat /tmp/healthyĀ and if the command return zero, we exit the code, and the liveness probe is considered successful. - Line 20Ā gives the value ofĀ
initialDelaySecondsĀ asĀ5, which tells Kubernetes to start the liveness probe afterĀ5Ā seconds elapse from the pod start. - Line 21Ā gives the value ofĀ
periodSecondsĀ asĀ5, which tells Kubernetes to do a liveness check everyĀ5Ā seconds after the first one.
Using an HTTP request for a liveness probe
Letās look at an example of using an HTTP request for a liveness probe.
In the code snippet above, the pod has a single container. Letās look at what each line does in some detail.
- Line 13 defines the liveness probe.
- We are using the
httpGeton line 14 to indicate that the liveness probe is an HTTP get request. - Line 15-19 provide the HTTP get request parameters. The liveness probe will succeed if the HTTP request returns
200. - Line 20 and 21 indicate the
initialDelaySecondsandperiodSeconds, both of which have been explained in the previous section.
Using TCP for a liveness probe
Letās look at an example of using TCP for a liveness probe.
In the code snippet above, the pod has a single container. Letās look at what each line does in some detail.
- Line 13 defines the liveness probe.
- We are using the
tcpSocketon line 14 to indicate that the liveness probe is a TCP request. - Line 15 indicates that the TCP request will be made on port
8080. The liveness probe will succeed if the TCP socket connection to port8080succeeds. - Line 16 and 17 indicate the
initialDelaySecondsandperiodSeconds, both of which have been explained in the previous section.
Conclusion
Liveness probes help the kubelet know when to restart your container. There are multiple ways to configure a liveness probe, and the application owner can choose what is best for the application.