Implementing Docker Compose Health Checks for Laravel Applications

Monitor your Laravel app’s health with Docker Compose health checks, preventing downtime and ensuring robust performance.

Docker Compose Health Checks for Laravel

Running a Laravel application inside Docker containers provides portability and consistency across development and production environments. However, containers can crash, become unresponsive due to unhandled exceptions, or lose database connectivity without stopping the container process itself.

Without explicit health checks, Docker and container orchestrators assume an unresponsive container is still healthy simply because its primary process (like PHP-FPM or Nginx) has not exited. This tutorial guides you through implementing Docker Compose health checks for your Laravel application, covering application health endpoints, database and Redis dependencies, resilient restart policies, and automated validation.

Prerequisites: Installing Docker Compose and Laravel

Before setting up health checks, verify that Docker and the modern Docker Compose v2 plugin are installed on your machine.

Verify your Docker and Docker Compose installation:

docker --version
docker compose version

If you do not have Docker Compose installed, follow Docker’s official installation instructions for your operating system or install the docker-compose-plugin package on Ubuntu/Debian:

sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin

Verify that your user has permissions to run Docker commands without sudo:

sudo usermod -aG docker $USER

Next, ensure you have a Laravel 11 application directory ready. If creating a new project:

composer create-project laravel/laravel health-check-example
cd health-check-example

Defining Health Checks in Laravel: Understanding the Basics

A container health check requires an internal mechanism to verify that application dependencies (such as the database connection and cache store) are operating properly.

In Laravel 11, you can use the built-in /up health endpoint configured in bootstrap/app.php, or implement a dedicated /health route that performs real readiness probes against your database and cache.

Add a robust health check route in routes/web.php:

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;

Route::get('/health', function () {
    $checks = [
        'database' => false,
        'cache' => false,
    ];

    try {
        DB::connection()->getPdo();
        $checks['database'] = true;
    } catch (\Throwable $e) {
        report($e);
    }

    try {
        Cache::put('health_check_ping', true, 10);
        $checks['cache'] = Cache::get('health_check_ping') === true;
    } catch (\Throwable $e) {
        report($e);
    }

    $isHealthy = ! in_array(false, $checks, true);

    return response()->json([
        'status' => $isHealthy ? 'healthy' : 'unhealthy',
        'checks' => $checks,
        'timestamp' => now()->toIso8601String(),
    ], $isHealthy ? 200 : 503);
});

This endpoint returns HTTP 200 OK when all critical services respond, and HTTP 503 Service Unavailable if the database or cache fails.

Additionally, for CLI-based container health checking, you can create a lightweight Artisan command:

php artisan make:command HealthCheckCommand

Inside app/Console/Commands/HealthCheckCommand.php:

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class HealthCheckCommand extends Command
{
    protected $signature = 'health:check';
    protected $description = 'Verify that application core services are operational';

    public function handle(): int
    {
        try {
            DB::connection()->getPdo();
            Cache::put('health_cli_ping', true, 10);

            $this->info('All services are healthy.');
            return Command::SUCCESS;
        } catch (\Throwable $e) {
            $this->error('Health check failed: ' . $e->getMessage());
            return Command::FAILURE;
        }
    }
}

Creating a Docker Compose File for Your Laravel Application

Now, structure your docker-compose.yml file to run your Laravel application (app), MySQL database (db), and Redis cache (redis) with consistent naming.

Create docker-compose.yml in your project root:

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: laravel_app
    ports:
      - "8000:8000"
    environment:
      APP_ENV: local
      APP_DEBUG: "true"
      DB_CONNECTION: mysql
      DB_HOST: db
      DB_PORT: 3306
      DB_DATABASE: laravel
      DB_USERNAME: laravel_user
      DB_PASSWORD: secret_password
      CACHE_STORE: redis
      REDIS_HOST: redis
      REDIS_PORT: 6379
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_healthy
    restart: unless-stopped

  db:
    image: mysql:8.0
    container_name: laravel_db
    environment:
      MYSQL_DATABASE: laravel
      MYSQL_USER: laravel_user
      MYSQL_PASSWORD: secret_password
      MYSQL_ROOT_PASSWORD: root_secret_password
    volumes:
      - db_data:/var/lib/mysql
    restart: unless-stopped

  redis:
    image: redis:alpine
    container_name: laravel_redis
    volumes:
      - redis_data:/data
    restart: unless-stopped

volumes:
  db_data:
  redis_data:

Notice the depends_on configuration with condition: service_healthy. This prevents the Laravel application from booting until MySQL and Redis have passed their health checks.

Implementing Health Checks with Docker Compose

Now attach a healthcheck definition to your application service.

You can check your application either via HTTP using curl against your /health endpoint, or using your Artisan command:

  app:
    build:
      context: .
      dockerfile: Dockerfile
    # ... other configuration ...
    healthcheck:
      test: ["CMD-SHELL", "curl -f http://localhost:8000/health || exit 1"]
      interval: 15s
      timeout: 5s
      retries: 3
      start_period: 20s

Parameters explained:

  • test: The shell command Docker executes inside the container.
  • interval: How frequently Docker runs the test (e.g., every 15 seconds).
  • timeout: Maximum duration Docker waits for the command to return before counting it as a failure.
  • retries: How many consecutive failed checks are required before the container is marked unhealthy.
  • start_period: A grace period allowing the application to bootstrap without premature failure flags.

Configuring Database and Cache Health Checks

Next, configure the native health checks for MySQL and Redis in docker-compose.yml.

1. MySQL Health Check

MySQL includes mysqladmin inside its official container, which allows checking daemon responsiveness without third-party tools:

  db:
    image: mysql:8.0
    # ... environment variables ...
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-proot_secret_password"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 30s

2. Redis Health Check

Redis includes redis-cli, allowing a lightweight ping probe:

  redis:
    image: redis:alpine
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 3s
      retries: 3

With these definitions in place, Docker continuously probes both storage dependencies, guaranteeing that dependent containers wait until the services are fully ready to accept queries.

Using Environment Variables to Simplify Health Check Configuration

Hardcoding passwords and parameters in docker-compose.yml is risky. Extract these configurations into environment variables.

In your docker-compose.yml:

services:
  db:
    image: mysql:8.0
    environment:
      MYSQL_DATABASE: ${DB_DATABASE:-laravel}
      MYSQL_USER: ${DB_USERNAME:-laravel_user}
      MYSQL_PASSWORD: ${DB_PASSWORD:-secret_password}
      MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:-root_secret_password}
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${DB_ROOT_PASSWORD:-root_secret_password}"]
      interval: 10s
      timeout: 5s
      retries: 5

Now define these variables securely in your .env file:

DB_DATABASE=laravel
DB_USERNAME=laravel_user
DB_PASSWORD=secret_password
DB_ROOT_PASSWORD=root_secret_password

This approach allows developers and CI/CD pipelines to alter credentials without modifying the Compose file structure.

Testing Your Laravel Application’s Health Checks

Once your Compose configuration is complete, validate that health checks behave as expected.

1. Start the Containers

Launch the stack in detached mode:

docker compose up -d

2. Monitor Container Health Status

Check the status of your containers using docker compose ps:

docker compose ps

You should see (health: starting) transition into (healthy):

NAME            IMAGE          COMMAND                  SERVICE      STATUS
laravel_app     app:latest     "docker-php-entry..."    app          Up 45s (healthy)
laravel_db      mysql:8.0      "docker-entrypoint..."   db           Up 50s (healthy)
laravel_redis   redis:alpine   "docker-entrypoint..."   redis        Up 50s (healthy)

3. Inspect Detailed Health Check Logs

To inspect the raw command output and failure logs of the health check:

docker inspect --format='{{json .State.Health}}' laravel_app | jq

This output displays the exact timestamps, exit codes, and output from recent probes.

4. Simulating a Failure

To test self-healing or alert responses, simulate a database failure by pausing the database container:

docker compose pause db

Within your configured retry window (e.g. 30–45 seconds), running docker compose ps will show laravel_app transitioning from (healthy) to (unhealthy) as the /health route returns HTTP 503.

Resume the database:

docker compose unpause db

Docker will detect the recovery on subsequent check intervals and automatically restore the container status to (healthy).

By implementing structured health checks across your Laravel application and its backing services, you ensure reliable orchestration, zero-downtime rolling deployments, and immediate visibility into operational health.

Frequently Asked Questions

What are Docker Compose health checks and why do I need them?

Docker Compose health checks allow you to monitor the status of your containers and take corrective action when they fail. They’re essential for ensuring your application remains available and resilient in production environments.

How can I avoid a common pitfall where my Docker container crashes without any indication of what went wrong?

Make sure to implement logging and monitoring tools within your containers, such as Logrotate and Prometheus, to provide visibility into potential issues before they cause downtime.

What’s the difference between using Docker Compose health checks and other monitoring tools like Prometheus or New Relic?

Docker Compose health checks are specifically designed for container orchestration and provide a simple way to define and manage application health. While other tools offer more advanced features, they may require additional setup and configuration compared to Docker Compose.

How can I configure database connections and cache performance monitoring within my Laravel application using Docker Compose?

You’ll need to create a docker-compose.yml file that includes environment variables for your database connection settings, as well as configurations for cache performance monitoring tools like Redis or Memcached.

What’s the best practice for implementing health checks in a Laravel application using Docker Compose?

Use a combination of environment variables and configuration files to define health checks, ensuring they’re easily maintainable and scalable as your application grows.

Comments

comments