diff --git a/CHANGELOG.md b/CHANGELOG.md index a9462355..9ef52663 100644 --- a/CHANGELOG.md +++ b/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. diff --git a/docs/healthcheck.md b/docs/healthcheck.md index c4edee1a..2e414817 100644 --- a/docs/healthcheck.md +++ b/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 +``` diff --git a/healthcheck.go b/healthcheck.go new file mode 100644 index 00000000..171055fc --- /dev/null +++ b/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) +} diff --git a/main.go b/main.go index 2c2faea6..148fa9db 100644 --- a/main.go +++ b/main.go @@ -31,6 +31,10 @@ func initialize() { } func main() { + if len(os.Args) > 1 && os.Args[1] == "health" { + healthcheck() + } + initialize() defer shutdownVips()