
The worst failures are the silent ones: the 2 a.m. backup that stopped working three weeks ago, the cron job that exits with an error nobody reads, the disk that fills up on a Sunday.
ntfy (pronounced "notify") fixes the "nobody told me" part with almost no setup. It's an open-source, HTTP-based publish/subscribe service. Your script sends an HTTP request to a topic, and your phone, subscribed to that topic, buzzes. There's no sign-up, no API key, and no SDK to install.
flowchart LR
A["Script or cron job"] -->|"curl POST /my-topic"| B["ntfy server: ntfy.sh or self-hosted"]
B -->|"push notification"| C["Phone app subscribed to my-topic"]Your first alert in 60 seconds
Install the ntfy app (Android or iOS) and subscribe to a topic name. A web app is also available.
From any terminal:
curl -d "Backup successful" ntfy.sh/my-topicYour phone buzzes. Topics are created on the fly, so there's nothing to set up first.
Important: on the public server the topic name is effectively the password. Anyone who knows or guesses it can read and publish to it. Don't use
alertsorbackups; use something random, likealerts-$(openssl rand -hex 8). See "Locking it down" below for the proper fix.
Make alerts useful with headers
A bare message is fine for testing. A few headers turn it into something you can triage at a glance:
curl \
-H "Title: Disk almost full" \
-H "Priority: high" \
-H "Tags: warning" \
-H "Click: https://grafana.example.com/d/disk" \
-d "/var is at 93% on web-1" \
ntfy.sh/my-topicTitle replaces the default topic-name title.
Priority accepts
min,low,default,highandurgent(or 1 to 5). Higher priorities vibrate and sound more insistently, so reserveurgentfor things worth waking up for.Tags are comma-separated; names that match emoji short codes (
warning,white_check_mark,rotating_light) show up as emoji.Click opens a URL when you tap the notification. There are also
Attach,Actions(buttons) andEmailheaders if you need them.
Wire it into your scripts
Put one helper in a file you can source everywhere. It has a timeout and swallows its own errors, so a broken notification never breaks the job it's reporting on.
# ~/bin/notify.sh
NTFY_URL="${NTFY_URL:-https://ntfy.sh}"
notify() { # usage: notify "Title" "Message" [priority] [tags]
local auth=()
[ -n "$NTFY_TOKEN" ] && auth=(-H "Authorization: Bearer $NTFY_TOKEN")
curl -fsS -m 10 --retry 2 "${auth[@]}" \
-H "Title: $1" -H "Priority: ${3:-default}" -H "Tags: ${4:-bell}" \
-d "$2" "$NTFY_URL/$NTFY_TOPIC" > /dev/null || true
}A backup job that reports its own result:
#!/usr/bin/env bash
set -eo pipefail
source ~/bin/notify.sh
export NTFY_TOPIC="alerts-xxxxxxxx"
rc=0
rsync -a --delete ~/data/ backup:/srv/backups/data/ || rc=$?
if [ "$rc" -eq 0 ]; then
notify "Backup OK" "$(hostname): rsync finished" low white_check_mark
else
notify "Backup FAILED" "$(hostname): rsync exited with code $rc" urgent warning
fiCatch any failure in a script with a trap:
set -eEo pipefail
trap 'notify "Job failed" "$(basename "$0") failed at line $LINENO" urgent rotating_light' ERRThe capital E matters: without it, the trap doesn't fire for commands that fail inside functions.
From Python:
import os
import requests
NTFY_URL = "https://ntfy.example.com/alerts"
NTFY_TOKEN = os.environ["NTFY_TOKEN"] # tk_... token; skip the header on an open topic
def notify(msg, title="Script", priority="default"):
try:
requests.post(
NTFY_URL,
data=msg.encode("utf-8"),
headers={
"Title": title,
"Priority": priority,
"Authorization": f"Bearer {NTFY_TOKEN}",
},
timeout=10,
)
except requests.RequestException:
pass # never let the alert break the jobOne habit that pays off: alert on failure loudly, and on success quietly (low priority). A daily "OK" message that suddenly doesn't arrive is itself a signal.
Locking it down
The public server has no accounts for anonymous use, so a hard-to-guess topic is your only protection. If you want real access control, you have two options: reserve topics with an account on ntfy.sh, or run your own server.
Self-hosting
Self-hosting is a single container. Create a server.yml:
base-url: "https://ntfy.example.com" # required for attachments, iOS and more
cache-file: "/var/cache/ntfy/cache.db"
auth-file: "/var/lib/ntfy/user.db"
auth-default-access: "deny-all" # see the warning below
behind-proxy: true
upstream-base-url: "https://ntfy.sh" # only needed for instant iOS notificationsWarning:
auth-default-accessdefaults toread-write, which means a fresh server lets anyone who can reach it publish and read any topic. Set it todeny-allbefore exposing the server.
Then a docker-compose.yml:
services:
ntfy:
image: binwiederhier/ntfy
command: serve
restart: unless-stopped
ports:
- "127.0.0.1:2586:80" # put a reverse proxy with HTTPS in front
volumes:
- ./server.yml:/etc/ntfy/server.yml:ro
- ./cache:/var/cache/ntfy
- ./lib:/var/lib/ntfyCreate users and a token, and give scripts write-only access:
docker compose up -d
docker compose exec ntfy ntfy user add --role=admin me # for your phone (asks for a password)
docker compose exec ntfy ntfy user add scripts # for your jobs (asks for a password)
docker compose exec ntfy ntfy access scripts 'alerts*' write-only
docker compose exec ntfy ntfy token add scripts # prints tk_...Your scripts now authenticate with that token:
export NTFY_URL="https://ntfy.example.com"
export NTFY_TOKEN="tk_..."A leaked script token can then only publish to alerts*. It can't read your notifications or touch other topics.
iOS note: Apple only allows push notifications through its own service, so a self-hosted server relays a tiny "poll request" (just a message ID, not the content) via ntfy.sh. That's what upstream-base-url enables. The app then fetches the real message from your server. Android doesn't need this.
Gotchas
Rate limits on the public server. Free use is limited (a burst of 60 requests, then roughly one every few seconds, plus a daily message cap). A loop that alerts on every failure can hit it, so send one summary per run instead. Limits can change, so check the docs. On your own server there are still default limits per client, but you can raise them in
server.yml(for examplevisitor-request-limit-burst).Cron has a minimal environment. Use absolute paths and set
NTFY_TOPICandNTFY_TOKENinside the script or the crontab, or your alerts will quietly never fire.Don't send secrets. Messages pass through the server and your phone's notification system. Send "backup failed on db-1", not the connection string.
Message size. Long bodies (over about 4 KB on the public server) are converted into attachments. Keep alerts short and link to details with
Click.Non-ASCII titles. Some HTTP libraries mangle UTF-8 in headers. If you see
?characters, RFC 2047-encode the header.ntfy tells you when something ran and failed, not when it never ran. If the server, the cron daemon or the whole machine is down, nothing gets sent. Pair it with a dead-man's switch such as Healthchecks.io for jobs that must run on schedule.
Wrap-up
ntfy is one of those tools that takes five minutes to adopt and then ends up in every script you write. Start with a random topic and the notify helper above. If you end up with more than a handful of jobs, or you want proper access control, move to a self-hosted server with a write-only token for your scripts.
Comments0
Log in to join the discussion.
No comments yet.