Skip
Arish's avatar

31. Health Checks


Dockerfile Health Check

dockerfile
1HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
2  CMD curl -f http://localhost:3000/health || exit 1

Compose Health Check

yaml
1services:
2  web:
3    healthcheck:
4      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
5      interval: 30s
6      timeout: 10s
7      retries: 3
8      start_period: 40s
9
10  db:
11    image: postgres:15
12    healthcheck:
13      test: ["CMD-SHELL", "pg_isready -U postgres"]
14      interval: 10s
15      timeout: 5s
16      retries: 5

Rails Health Endpoint

ruby
1# config/routes.rb
2get '/health', to: 'health#show'
3
4# app/controllers/health_controller.rb
5class HealthController < ApplicationController
6  def show
7    ActiveRecord::Base.connection.execute('SELECT 1')
8    render json: { status: 'ok' }, status: :ok
9  rescue StandardError => e
10    render json: { status: 'error', message: e.message }, status: :service_unavailable
11  end
12end

Checking Health

bash
1docker inspect --format='{{.State.Health.Status}}' container_name