#!/usr/bin/env bash set -euo pipefail #: "${GOTIFY_URL:?Set GOTIFY_URL (e.g. https://gotify.lan.ddnsgeek.com)}" #: "${GOTIFY_TOKEN:?Set GOTIFY_TOKEN (AAM..CtNmUGoNIV)}" GOTIFY_URL="${GOTIFY_URL}" GOTIFY_TOKEN="${GOTIFY_TOKEN}" STATE_DIR="./docker-health-alert" STATE_FILE="${STATE_DIR}/last_unhealthy.txt" mkdir -p "$STATE_DIR" # Collect unhealthy running containers (ignore those with no healthcheck) unhealthy="$( docker ps -q | while read -r id; do status="$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}no-healthcheck{{end}}' "$id")" name="$(docker inspect --format '{{.Name}}' "$id" | sed 's|^/||')" if [[ "$status" == "unhealthy" ]]; then echo "$name" fi done | sort )" # Only alert on change last="$(cat "$STATE_FILE" 2>/dev/null || true)" if [[ "$unhealthy" != "$last" ]]; then if [[ -n "$unhealthy" ]]; then msg="Unhealthy containers: $(echo "$unhealthy" | paste -sd ', ' -)" title="Docker: UNHEALTHY" priority=8 else msg="All containers healthy again." title="Docker: RECOVERED" priority=4 fi curl -fsS -X POST "${GOTIFY_URL%/}/message" \ -H "X-Gotify-Key: ${GOTIFY_TOKEN}" \ -F "title=${title}" \ -F "message=${msg}" \ -F "priority=${priority}" >/dev/null printf "%s" "$unhealthy" > "$STATE_FILE" fi