天天看點

docker容器的健康狀态監控功能healthcheck

部落格作為學習筆記記錄,若有了解,表述錯誤,歡迎指出。

healthcheck是docker1.12版本引入的新功能,用于容器健康狀态監測

暫時k8s不支援docker的healthcheck功能,k8s由其之前就提供的liveness和readiness功能來實作healthcheck,docker引入healthcheck功能,估計也是向k8s學習的。

docker 的healthcheck

設定選項:

  • --interval=DURATION

     (default: 

    30s

    ),間隔
  • --timeout=DURATION

     (default: 

    30s

    ), 逾時時間
  • --start-period=DURATION

     (default: 

    0s

    ),初始化時間

          說明:在此期間的探測失敗将不計入最大重試次數。但是,如果健康檢查在啟動期間成功,則認為容器已啟動,所有連續的失敗都将計入最大重試次數。

  • --retries=N

     (default: 

    3

    ),當連續失敗指定次數後,容器狀态會變成unhealthy

格式:HEALTHCHECK [選項] CMD(分成shell格式和exec格式)。

如果有多個指令,則最後一個生效。

輸出: healthcheck指令執行的結果有以下幾種:

  • 0: success - the container is healthy and ready for use,容器成功運作,狀态健康
  • 1: unhealthy - the container is not working correctly,容器啟動異常
  • 2: reserved - do not use this exit code,未使用

舉個栗子:

用curl來判斷web服務是否正常,在dockerfile中定義healthcheck:

FROM nginx
RUN apt-get update && apt-get
install -y curl && rm -rf /var/lib/apt/lists/*
HEALTHCHECK --interval=5s --timeout=3s \
  CMD curl -fs http://localhost/ || exit 1
           

剛運作容器時,容器狀态為health:starting

$ docker container ls
CONTAINER ID        IMAGE               COMMAND                  CREATED           STATUS                            PORTS               NAMES
03e28eb00bd0        myweb:v1            "nginx -g 'daemon off"  3 seconds ago       Up 2 seconds (health: starting)  80/tcp, 443/tcp     web
           

過幾秒之後,狀态會變成healthy

$ docker container ls
CONTAINER ID        IMAGE               COMMAND                  CREATED            STATUS                    PORTS               NAMES
03e28eb00bd0        myweb:v1            "nginx -g 'daemon off"  18 seconds ago      Up 16 seconds (healthy)   80/tcp, 443/tcp     web
           

健康指令的輸出結果會存儲在健康狀态裡,可以用docker inspect來檢視,eg:

$ docker inspect --format '{{json .State.Health}}' web | python -m json.tool
           
#輸出為:
{
    "FailingStreak": 0,
    "Log": [
        {
            "End": "2016-11-25T14:35:37.940957051Z",
            "ExitCode": 0,
            "Output": "<!DOCTYPE
html>\n<html>\n<head>\n<title>Welcome to
nginx!</title>\n<style>\n   
body {\n        width: 35em;\n        margin: 0 auto;\n        font-family: Tahoma, Verdana, Arial,
sans-serif;\n   
}\n</style>\n</head>\n<body>\n<h1>Welcome to
nginx!</h1>\n<p>If you see this page, the nginx web server is
successfully installed and\nworking. Further configuration is
required.</p>\n\n<p>For online documentation and support please
refer to\n<a href=\"http://nginx.org/\">nginx.org</a>.<br/>\nCommercial
support is available at\n<a
href=\"http://nginx.com/\">nginx.com</a>.</p>\n\n<p><em>Thank
you for using nginx.</em></p>\n</body>\n</html>\n",
            "Start":
"2016-11-25T14:35:37.780192565Z"
        }
    ],
    "Status": "healthy"
}
           

REF:

https://docker_practice.gitee.io/image/dockerfile/healthcheck.html

https://docs.docker.com/engine/reference/builder/