浏览代码

imgproxy health command

DarthSim 5 年之前
父节点
当前提交
0f00870708
共有 4 个文件被更改,包括 59 次插入0 次删除
  1. 1 0
      CHANGELOG.md
  2. 12 0
      docs/healthcheck.md
  3. 42 0
      healthcheck.go
  4. 4 0
      main.go

+ 1 - 0
CHANGELOG.md

@@ -4,6 +4,7 @@
 ### Added
 - `IMGPROXY_NETWORK` config. Allows to bind on Unix socket.
 - `IMGPROXY_CACHE_CONTROL_PASSTHROUGH` config.
+- `imgproxy health` command.
 
 ### Fixed
 - Fix detection of SVG starting with a comment.

+ 12 - 0
docs/healthcheck.md

@@ -5,3 +5,15 @@ imgproxy comes with a built-in health check HTTP endpoint at `/health`.
 `GET /health` returns HTTP Status `200 OK` if the server is started successfully.
 
 You can use this for readiness/liveness probe when deploying with a container orchestration system such as Kubernetes.
+
+## imgproxy health
+
+imgproxy provides `imgproxy health` command that makes an HTTP request to the health endpoint based on `IMGPROXY_BIND` and `IMGPROXY_NETWORK` configs. It exits with `0` when the request is successful and with `1` otherwise. The command is handy to use with Docker Compose:
+
+```yaml
+healthcheck:
+  test: [ "CMD", "imgproxy", "health" ]
+  timeout: 10s
+  interval: 10s
+  retries: 3
+```

+ 42 - 0
healthcheck.go

@@ -0,0 +1,42 @@
+package main
+
+import (
+	"context"
+	"fmt"
+	"io/ioutil"
+	"net"
+	"net/http"
+	"os"
+)
+
+func healthcheck() {
+	network := conf.Network
+	bind := conf.Bind
+
+	strEnvConfig(&network, "IMGPROXY_NETWORK")
+	strEnvConfig(&bind, "IMGPROXY_BIND")
+
+	httpc := http.Client{
+		Transport: &http.Transport{
+			DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
+				return net.Dial(network, bind)
+			},
+		},
+	}
+
+	res, err := httpc.Get("http://imgproxy/health")
+	if err != nil {
+		fmt.Fprintln(os.Stderr, err.Error())
+		os.Exit(1)
+	}
+	defer res.Body.Close()
+
+	msg, _ := ioutil.ReadAll(res.Body)
+	fmt.Fprintln(os.Stderr, string(msg))
+
+	if res.StatusCode != 200 {
+		os.Exit(1)
+	}
+
+	os.Exit(0)
+}

+ 4 - 0
main.go

@@ -31,6 +31,10 @@ func initialize() {
 }
 
 func main() {
+	if len(os.Args) > 1 && os.Args[1] == "health" {
+		healthcheck()
+	}
+
 	initialize()
 	defer shutdownVips()