Liveness and Readiness Probes with Spring Boot – for k8s
In Kubernetes, the Liveness and Readiness Kubernetes concepts represent facets of the application state.
The Liveness state of an application tells whether the internal state is valid. If Liveness is broken, this means that the application itself is in a failed state and cannot recover from it. In this case, the best course of action is to restart the application instance. For example, an application relying on a local cache should fail its Liveness state if the local cache is corrupted and cannot be repaired.
The Readiness state tells whether the application is ready to accept client requests. If the Readiness state is unready, Kubernetes should not route traffic to this instance. If an application is too busy processing a task queue, then it could declare itself as busy until its load is manageable again.
Code Sample:
Endpoint Configuration
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class CustomEndpointConfiguration { @Bean public LivenessProbeEndpoint livenessProbeEndpoint() { return new LivenessProbeEndpoint(); } @Bean public ReadinessProbeEndpoint readinessProbeEndpoint() { return new ReadinessProbeEndpoint(); } } |
Liveness Probe
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.boot.actuate.health.Health; import org.springframework.stereotype.Component; @Component @Endpoint(id = "liveness-probe") public class LivenessProbeEndpoint { @ReadOperation public Health livenessProbe() { return Health.up().build(); } } |
Readiness Probe
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import com.myservice.service.MyCustomService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.boot.actuate.health.Health; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; @Component @Endpoint(id = "readiness-probe") public class ReadinessProbeEndpoint { @Autowired private ApplicationContext context; @ReadOperation public Health readinessProbe() { Health result = null; try { context.getBean(MyCustomService.class); result = Health.up().build(); } catch (Exception e) { result = Health.down().build(); } return result; } } |
Reference:
Liveness and Readiness Probes with Spring Boot
You (probably) need liveness and readiness probes