Bird
Raised Fist0
Dockerdevops~5 mins

Health checks in Compose in Docker - Commands & Configuration

Choose your learning style10 modes available
Introduction
Sometimes a service inside a container might start but not be ready to work. Health checks help Docker Compose know if a service is healthy and ready to use by running simple tests inside the container.
When you want to make sure a web server inside a container is fully ready before other services connect to it
When you run a database container and want to check if it is accepting connections
When you have multiple containers and want to restart a container automatically if it becomes unhealthy
When you want to delay starting dependent services until the main service is healthy
When you want to monitor the status of your containers easily with Docker Compose commands
Config File - docker-compose.yml
docker-compose.yml
version: '3.8'
services:
  web:
    image: nginx:1.23
    ports:
      - "8080:80"
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 5s

This Compose file defines a service named web using the nginx image.

The healthcheck section runs a command inside the container to check if the web server is responding.

  • test: The command to run for the health check. Here it tries to fetch the homepage using curl.
  • interval: How often to run the check (every 30 seconds).
  • timeout: How long to wait for the check to finish (10 seconds).
  • retries: How many times to retry before marking unhealthy (3 times).
  • start_period: Time to wait after container start before checking (5 seconds).
Commands
Starts the services defined in the docker-compose.yml file in detached mode so they run in the background.
Terminal
docker-compose up -d
Expected OutputExpected
Creating network "default" with the default driver Creating default_web_1 ... done
→
-d - Run containers in the background (detached mode)
Shows the status of the running containers including their health status.
Terminal
docker-compose ps
Expected OutputExpected
Name Command State Ports -------------------------------------------------------------------------------- default_web_1 nginx -g 'daemon off;' Up (healthy) 0.0.0.0:8080->80/tcp
Shows detailed health check results for the web container in JSON format.
Terminal
docker inspect --format='{{json .State.Health}}' default_web_1
Expected OutputExpected
{"Status":"healthy","FailingStreak":0,"Log":[{"Start":"2024-06-01T12:00:00Z","End":"2024-06-01T12:00:05Z","ExitCode":0,"Output":""}]}
Stops and removes the containers, networks, and volumes created by docker-compose up.
Terminal
docker-compose down
Expected OutputExpected
Stopping default_web_1 ... done Removing default_web_1 ... done Removing network default
Key Concept

If you remember nothing else from this pattern, remember: health checks let Docker Compose know if a container is ready and healthy by running simple commands inside it.

Common Mistakes
Not specifying a health check command or using a command that always succeeds
Docker will not be able to detect if the service is actually ready or healthy, so it may report unhealthy containers as healthy.
Use a command that truly tests the service readiness, like a curl request to a web server or a database connection test.
Setting too short intervals or timeouts for health checks
The container might be marked unhealthy too quickly during normal startup delays, causing unnecessary restarts.
Set reasonable intervals, timeouts, and start_period to allow the service enough time to start.
Ignoring health status in dependent services
Other services might start before the main service is healthy, causing failures or errors.
Use health check status to control service startup order or retries.
Summary
Define health checks in docker-compose.yml to test if a container service is ready.
Use docker-compose up to start services and docker-compose ps to see health status.
Inspect detailed health results with docker inspect and clean up with docker-compose down.

Practice

(1/5)
1. What is the main purpose of a health check in a Docker Compose service?
easy
A. To restart the container automatically
B. To verify if the container's application is running correctly
C. To build the container image
D. To expose ports to the host machine

Solution

  1. Step 1: Understand health check purpose

    Health checks run commands inside the container to confirm the app is working well.
  2. Step 2: Differentiate from other Docker tasks

    Restarting, building, and exposing ports are separate Docker tasks, not health checks.
  3. Final Answer:

    To verify if the container's application is running correctly -> Option B
  4. Quick Check:

    Health check = verify app status [OK]
Hint: Health checks confirm app health inside containers [OK]
Common Mistakes:
  • Confusing health checks with container restart policies
  • Thinking health checks build images
  • Mixing health checks with port mapping
2. Which of the following is the correct syntax to add a health check in a Docker Compose service?
easy
A. healthcheck: { run: "curl http://localhost" }
B. health_check: { command: "curl http://localhost" }
C. healthcheck: { test: ["CMD", "curl", "-f", "http://localhost"] }
D. healthcheck: { check: "curl http://localhost" }

Solution

  1. Step 1: Recall Docker Compose healthcheck syntax

    The correct key is 'healthcheck' with a 'test' array specifying the command.
  2. Step 2: Validate command format

    The 'test' must be an array starting with 'CMD' followed by the command and arguments.
  3. Final Answer:

    healthcheck: { test: ["CMD", "curl", "-f", "http://localhost"] } -> Option C
  4. Quick Check:

    Use 'healthcheck' with 'test' array [OK]
Hint: Use 'healthcheck' and 'test' array with CMD for commands [OK]
Common Mistakes:
  • Using wrong keys like 'health_check' or 'run'
  • Passing command as a string instead of array
  • Omitting 'CMD' in the test array
3. Given this Compose snippet, what will be the health status if the curl command fails?
healthcheck:
  test: ["CMD", "curl", "-f", "http://localhost"]
  interval: 10s
  retries: 3
medium
A. The container will be marked as unhealthy after 3 failed attempts
B. The container will restart automatically after the first failure
C. The container will ignore the failure and stay healthy
D. The container will stop immediately on failure

Solution

  1. Step 1: Understand retries and failure effect

    The health check runs every 10 seconds and allows 3 retries before marking unhealthy.
  2. Step 2: Identify container behavior on failure

    Failing the test 3 times marks the container unhealthy; it does not restart or stop automatically.
  3. Final Answer:

    The container will be marked as unhealthy after 3 failed attempts -> Option A
  4. Quick Check:

    Retries control unhealthy marking, not restart [OK]
Hint: Retries count failures before unhealthy status [OK]
Common Mistakes:
  • Assuming container restarts on health check failure
  • Thinking container stops immediately on failure
  • Ignoring the retries setting
4. You added this health check to your Compose file but it never reports healthy:
healthcheck:
  test: curl -f http://localhost || exit 1
  interval: 5s
  retries: 2
What is the problem?
medium
A. The test command must be an array starting with CMD
B. The interval value must be in milliseconds
C. Retries cannot be less than 3
D. The healthcheck key should be under volumes

Solution

  1. Step 1: Check healthcheck test syntax

    Docker Compose requires the test command as an array starting with 'CMD' or 'CMD-SHELL'.
  2. Step 2: Identify why string command fails

    Using a plain string without array causes Compose to ignore or fail the health check.
  3. Final Answer:

    The test command must be an array starting with CMD -> Option A
  4. Quick Check:

    Use array with CMD for test command [OK]
Hint: Healthcheck test must be array with CMD or CMD-SHELL [OK]
Common Mistakes:
  • Writing test as plain string instead of array
  • Misplacing healthcheck under wrong keys
  • Using invalid interval units
5. You want a service in Docker Compose to be considered healthy only if a custom script check.sh inside the container returns success within 5 seconds. Which Compose healthcheck configuration is best?
hard
A. healthcheck: test: ["CMD-SHELL", "./check.sh"] interval: 10s retries: 3
B. healthcheck: test: ["CMD-SHELL", "timeout 5s ./check.sh"] interval: 10s retries: 3
C. healthcheck: test: ["CMD", "./check.sh"] interval: 5s retries: 1
D. healthcheck: test: ["CMD", "./check.sh"] timeout: 5s interval: 10s retries: 3

Solution

  1. Step 1: Understand timeout usage in healthcheck

    The 'timeout' key sets max time for the test command to run; here 5 seconds is needed.
  2. Step 2: Choose correct test format and timing

    Using 'CMD' with './check.sh' is valid; 'timeout' controls max duration; interval and retries set frequency and tolerance.
  3. Final Answer:

    healthcheck: test: ["CMD", "./check.sh"] timeout: 5s interval: 10s retries: 3 -> Option D
  4. Quick Check:

    Use 'timeout' key to limit test duration [OK]
Hint: Use 'timeout' key to limit healthcheck command time [OK]
Common Mistakes:
  • Using shell timeout inside test instead of 'timeout' key
  • Confusing interval and timeout values
  • Omitting retries leading to quick unhealthy status
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard