Vishal Shivare
Vishal Shivare

Reputation: 45

How to integrate healthcheck with docker swarm?

I am trying to integrate healthcheck with docker swarm. I have created my own custom health check API to monitor the health of container. I am using following tag for healthcheck in yaml file:

healthcheck:
      test: curl -X GET -sf https://${HOSTNAME}:port/module_name/health || exit 0
      interval: 30s
      timeout: 3s
      retries: 25 

Here I have tried with different API responses like json object, 200 response, 500 response also tried with 0 and 1 returning value. But in each case docker is not able to understand the response of my health API. The behavior of container totally depends on whatever value I mentioned in test tag's exit code if I set exit 0 container is always healthy or if set exit 1 container is always unhealthy.

How the healthcheck will understand my custom API response? Ex: If my custom API returns 500 or 1 then healthcheck should consider this as there is something wrong and need to mark container as unhealthy.

Can anyone help me to understand how to use healthcheck with docker-swarm?

Upvotes: 0

Views: 1423

Answers (1)

LinPy
LinPy

Reputation: 18578

can include all the things in a script and call it using

healthcheck:
    test: ["CMD", "python", "/path/script.py" , "YOUR_HOSTNAME" ]

example script:

import requests
import sys

if len(sys.argv) < 2:
     print("Please supply the hostname")
     sys.exit(1)

hostname = sys.argv[1]
url = "http://%s/healthcheck" % hostname
try:
    get_url = requests.get(url)
    response = get_url.text
    if response == "1":
        print("expect to get 0 but get 1 with response code %s" % get_url.status_code)
        sys.exit(1)
except Exception as e:
    print(str(e))
    sys.exit(1)

Upvotes: 2

Related Questions