📜  healthcheck docker compose (1)

📅  最后修改于: 2023-12-03 15:15:30.071000             🧑  作者: Mango

Healthcheck in Docker Compose

Docker Compose is a tool for defining and running multi-container Docker applications. It provides a way to configure and link containers with a single configuration file called a Docker Compose file. One of the important features in Docker Compose is healthcheck.

What is Healthcheck?

Healthcheck is a mechanism to determine whether a container is running correctly. It allows you to define a command or script to run periodically inside a container to check its health status. The health status can be one of three values: starting, healthy, or unhealthy. If a container is unhealthy, Docker Compose will stop or restart the container.

How to Define Healthcheck in Docker Compose?

To define a healthcheck in Docker Compose, you need to add the following lines to your service configuration:

healthcheck:
  test: [CMD, ARG, ...]
  interval: Xs
  timeout: Xs
  retries: N

test defines the command or script to run periodically inside the container to check its health status. It can be a single string or a list of strings. For example:

healthcheck:
  test: ["CMD-SHELL", "curl --fail http://localhost:8080/health || exit 1"]

This defines a healthcheck that checks if an HTTP server is running on port 8080 by sending a GET request to the /health endpoint. If the request fails, the healthcheck will exit with an error.

interval defines the time interval between health status checks. The default interval is 30 seconds.

timeout defines the maximum time allowed for a healthcheck to run. The default timeout is 30 seconds.

retries defines the number of times to retry a failed healthcheck before declaring the container as unhealthy. The default number of retries is 3.

How to Use Healthcheck in Docker Compose?

To use healthcheck in Docker Compose, you need to add the healthcheck configuration to your service definition. For example:

version: '3'
services:
  web:
    image: nginx
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost"]
      interval: 30s
      timeout: 30s
      retries: 3

This example defines a healthcheck for an Nginx container. The healthcheck runs the curl -f http://localhost command every 30 seconds. If the command returns an error, the healthcheck will retry up to 3 times before declaring the container as unhealthy.

Conclusion

In conclusion, healthchecks are an important feature of Docker Compose. They allow you to ensure that your containerized applications are running correctly and take appropriate actions if they are not. By following the guidelines outlined in this article, you can easily define and use healthchecks in your Docker Compose projects.