Microservice Health Check Instance Docker

Abstract: Resolve premature traffic routing to uninitialized Spring Boot containers by configuring separate liveness and readiness probes for Docker health checks.

Created: 2026-10-23 by
Spring Boot 2.3 introduced a critical separation of health indicators into distinct liveness and readiness probes, replacing the single /actuator/health endpoint used in earlier versions. To ensure reliable container orchestration in Docker and Kubernetes, you must configure separate endpoints for startup completion and service availability. This prevents premature traffic routing to containers that are initialized but not yet ready to handle requests.

Understanding Liveness vs Readiness Probes

In modern microservice architectures, distinguishing between a process being alive and a service being ready is essential for stability. The liveness probe checks if the application process is running and responsive. If this check fails, Kubernetes assumes the container is in a bad state and restarts it immediately. The readiness probe, however, verifies if the application can accept traffic. This includes checking database connections, cache availability, or external API dependencies. Previously, Spring Boot exposed a single health status at /actuator/health. This forced operators to choose between restarting unhealthy apps or blocking traffic to uninitialized ones. By splitting these concerns, you gain granular control over deployment lifecycle management. The liveness endpoint should only monitor the JVM itself, while the readiness endpoint monitors all dependent services.

Configuring Spring Boot Actuators

To implement this separation, you need to enable the specific actuator endpoints in your application.properties or application.yml. Ensure that the management endpoints are exposed via HTTP so that the orchestrator can reach them. management.endpoints.web.exposure.include=health,liveness,readiness Next, define the mapping paths for these endpoints. While Spring Boot provides default mappings, explicitly setting them ensures clarity across different environments. The liveness probe typically maps to /actuator/health/liveness, and the readiness probe maps to /actuator/health/readiness. management.endpoint.health.liveness-state.enabled=true management.endpoint.health.readiness-state.enabled=true You can also customize the response codes. By default, both return HTTP 200 for success. You might want to return 503 Service Unavailable if the application is not ready, which signals Kubernetes to stop sending traffic until the next successful check.

Docker Container Health Checks

While Kubernetes handles the orchestration logic, Docker also supports health checks during local development or standalone deployments. You can define a health check in your Dockerfile using the HEALTHCHECK instruction. This command runs periodically inside the container to verify its operational status.
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
  CMD curl -f http://localhost:8080/actuator/health/liveness || exit 1
The --start-period flag is crucial for Spring Boot applications. It gives the JVM time to initialize beans and connect to databases before the first health check triggers. Without this delay, the container might be marked as unhealthy before the application has fully started, leading to unnecessary restarts. For production, rely on Kubernetes probes rather than Docker health checks, as K8s offers more sophisticated retry policies and integration with pod lifecycle events. However, keeping the Docker health check consistent with the liveness probe ensures parity between local and remote environments. Image Pull Backoff Error: Could Not Pull Image from Docker Registry often occurs when base images are misconfigured, but proper health checks help diagnose runtime issues after the image is successfully loaded.

Kubernetes Probe Configuration

In your Kubernetes Deployment manifest, define both liveness and readiness probes for each container. These probes tell the kubelet how to interact with your application.
spec:
  containers:
  - name: my-service
    image: my-service:latest
    livenessProbe:
      httpGet:
        path: /actuator/health/liveness
        port: 8080
      initialDelaySeconds: 30
      periodSeconds: 10
    readinessProbe:
      httpGet:
        path: /actuator/health/readiness
        port: 8080
      initialDelaySeconds: 5
      periodSeconds: 5
The initialDelaySeconds for liveness should be higher than readiness because the application needs more time to become fully operational. The readiness probe can start checking sooner, as it only needs to verify basic connectivity. If the liveness probe fails, Kubernetes kills the pod and starts a new one. If the readiness probe fails, Kubernetes removes the pod from the service endpoint list, stopping traffic flow but keeping the pod running. This allows developers to fix transient issues without losing state or triggering full restarts unnecessarily. Troubleshooting Java Connect Exception: Connection Refused in Docker Compose Spring Boot Keycloak highlights common dependency failures that readiness probes are designed to catch gracefully.

Custom Health Indicators

Spring Boot allows you to create custom health indicators for specific components. Implement the HealthIndicator interface to add checks for Redis, RabbitMQ, or custom APIs. These indicators contribute to the overall readiness status.
@Component
public class CustomServiceHealthIndicator implements HealthIndicator {
    @Override
    public Health health() {
        try {
            // Check connection to custom service
            if (isConnected()) {
                return Health.up().withDetail("status", "connected").build();
            } else {
                return Health.down().withDetail("error", "connection failed").build();
            }
        } catch (Exception e) {
            return Health.down(e).build();
        }
    }
}
By aggregating these checks, the readiness probe provides a comprehensive view of system health. This ensures that traffic is only routed to instances where all critical dependencies are functioning correctly.

Frequently Asked Questions

What happens if the liveness probe fails?

Kubernetes will immediately terminate the container and schedule a new one. This is intended for unrecoverable states where the application is stuck or deadlocked.

Can I use the same endpoint for both probes?

No, using the same endpoint defeats the purpose of separation. A single endpoint cannot distinguish between a JVM crash and a temporary dependency failure.

How do I test health endpoints locally?

Run your Spring Boot application and navigate to http://localhost:8080/actuator/health/liveness in your browser or use curl to verify the JSON response.

What if my database is down?

The liveness probe should still pass because the JVM is running. The readiness probe should fail, preventing traffic from reaching the pod until the database is restored.

Is it safe to remove the readiness probe?

Removing it risks routing traffic to pods that are initializing or have failed dependencies, leading to increased error rates and poor user experience.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More