0
0
Spring Bootframework~5 mins

Health checks in Docker in Spring Boot

Choose your learning style9 modes available
Introduction

Health checks help Docker know if your Spring Boot app is running well or needs restarting. This keeps your app reliable and available.

When you want Docker to restart your app if it crashes or becomes unresponsive.
When running your Spring Boot app in a container and you want to monitor its status automatically.
When deploying microservices and you need to ensure each service is healthy before sending traffic.
When you want to avoid manual checks and let Docker manage app health.
When you want to improve uptime by detecting problems early.
Syntax
Spring Boot
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 CMD curl -f http://localhost:8080/actuator/health || exit 1

This Dockerfile instruction tells Docker how to check your app's health.

It uses Spring Boot's built-in /actuator/health endpoint to verify the app is running.

Examples
Basic health check with default timing, checks the health endpoint.
Spring Boot
HEALTHCHECK CMD curl -f http://localhost:8080/actuator/health || exit 1
Health check runs every 10 seconds and waits up to 3 seconds for a response.
Spring Boot
HEALTHCHECK --interval=10s --timeout=3s CMD curl -f http://localhost:8080/actuator/health || exit 1
Gives the app 20 seconds to start before checking and retries 5 times before failing.
Spring Boot
HEALTHCHECK --start-period=20s --retries=5 CMD curl -f http://localhost:8080/actuator/health || exit 1
Sample Program

This Dockerfile builds a container for a Spring Boot app. It exposes port 8080 and adds a health check that calls the app's /actuator/health endpoint every 30 seconds. If the app is unhealthy, Docker can restart it automatically.

Spring Boot
FROM openjdk:17-jdk-slim
WORKDIR /app
COPY target/myapp.jar ./myapp.jar
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD curl -f http://localhost:8080/actuator/health || exit 1
ENTRYPOINT ["java", "-jar", "myapp.jar"]
OutputSuccess
Important Notes

Make sure your Spring Boot app has the actuator dependency and the health endpoint enabled.

You can customize the health endpoint or create your own for more specific checks.

Use Docker commands like docker ps and docker inspect to see health status.

Summary

Health checks let Docker watch your Spring Boot app's health automatically.

Use the /actuator/health endpoint as the check target.

Configure timing options to fit your app's startup and response times.