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
as5
, which tells Kubernetes to start the liveness probe after5
seconds elapse from the pod start. - Line 21 gives the value of
periodSeconds
as5
, which tells Kubernetes to do a liveness check every5
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
httpGet
on 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
initialDelaySeconds
andperiodSeconds
, 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
tcpSocket
on 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 port8080
succeeds. - Line 16 and 17 indicate the
initialDelaySeconds
andperiodSeconds
, 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.