Chapter 11 · Lesson 2 of 10
Monitoring and logs

Uptime checks with a bash script and a systemd timer

An uptime check is a script on a different machine that requests your URL on a schedule, checks the status and body, and sends a webhook alert only when the state changes.

By the end you will

Run a script from a second machine that checks your site every minute and sends one alert per outage, not one per failure.

Time
25 min
Level
Intermediate
Check
4 questions
You need
  • A second Linux machine or VPS to run the check from
  • A chat or alert webhook URL

An uptime check is a small script on a different machine that requests your URL on a schedule, tests the status code and the response body, and sends a webhook message when the state changes. Run it from a second server so it still works when the monitored one is down, and keep a state file so one outage produces one alert instead of one per minute.

How it works#

The script uses curl -fsS --max-time 10. The -f flag makes curl exit non-zero on HTTP errors such as 500, -sS hides the progress meter but still prints errors, and --max-time stops a hung server from blocking the script. The script also looks for an expected string in the body, because a page can return 200 and still be an error screen. It compares the result to the last result stored in a file and calls a webhook only when they differ.

A scheduler runs the script every minute. Both cron and systemd timers work. The check must live on another host. If it runs on the monitored server, a power loss or network cut silences it exactly when you need it. See what to monitor first for why.

Step 1: Write the script#

Save this as /usr/local/bin/check-site.sh on the second machine:

bash
#!/usr/bin/env bash
set -u

URL="https://example.com/"
EXPECT="Welcome"
HOOK="https://example.com/hook"
TOKEN="change-me"
STATE_FILE="/var/lib/check-site/state"

mkdir -p "$(dirname "$STATE_FILE")"
prev="$(cat "$STATE_FILE" 2>/dev/null || echo up)"

body="$(curl -fsS --max-time 10 "$URL" 2>/dev/null)"
rc=$?

if [ "$rc" -eq 0 ] && printf '%s' "$body" | grep -q "$EXPECT"; then
  now=up
else
  now=down
fi

if [ "$now" != "$prev" ]; then
  curl -fsS --max-time 10 -X POST "$HOOK" \
    -H "Authorization: Bearer $TOKEN" \
    -d "{\"text\":\"$URL is $now\"}" >/dev/null 2>&1
  echo "$now" > "$STATE_FILE"
  echo "alert sent: $URL is $now"
else
  echo "ok $URL (state unchanged: $now)"
fi

Replace https://example.com/hook and change-me with your real webhook and token, and never commit the real values to a repository. Make the script executable:

bash
sudo chmod 755 /usr/local/bin/check-site.sh
sudo mkdir -p /var/lib/check-site

The state file is written only after the webhook call, but the script writes it either way here to keep the logic short. If you prefer to retry a failed alert next run, write the file only when the webhook call succeeds.

Step 2: Run it by hand#

Run the script as the user that will own the schedule:

bash
sudo /usr/local/bin/check-site.sh

A healthy site prints ok https://example.com/ (state unchanged: up). To test the alert path, temporarily set EXPECT to a string that is not on the page. You should get one down message in your channel, and one recovery message after you restore the value.

Step 3: Schedule it with cron#

The shortest option is one line in sudo crontab -e:

output
* * * * * /usr/local/bin/check-site.sh >> /var/log/check-site.log 2>&1

This runs every minute and appends output to a log. Rotate that log (see log basics with journald and logrotate) or it will grow slowly forever. The cron basics are in schedule tasks with cron.

Step 4: Or schedule it with a systemd timer#

A timer gives you journal logs and a visible failed state. Create /etc/systemd/system/check-site.service:

ini
[Unit]
Description=Check site uptime

[Service]
Type=oneshot
ExecStart=/usr/local/bin/check-site.sh

Then /etc/systemd/system/check-site.timer:

ini
[Unit]
Description=Run the site check every minute

[Timer]
OnBootSec=1min
OnUnitActiveSec=1min
AccuracySec=5s

[Install]
WantedBy=timers.target

OnUnitActiveSec=1min runs the service one minute after its last activation. If you prefer wall clock times, use OnCalendar=*:0/1 instead (every minute). Enable it:

bash
sudo systemctl daemon-reload
sudo systemctl enable --now check-site.timer
systemctl list-timers check-site.timer

Read results with journalctl -u check-site.service --since "10 minutes ago". More on units is in run a service with systemd.

Check it worked#

  • systemctl list-timers check-site.timer shows a next run within a minute.
  • journalctl -u check-site.service -n 5 shows ok ... state unchanged: up lines.
  • Changing EXPECT to a missing word sends exactly one down message, not one per minute.
  • Restoring it sends exactly one recovery message.
  • Stop the monitored service for two minutes and confirm the alert arrives on your phone.

Edge cases and gotchas#

  • Alert spam. Without a state file you get a message every run during an outage. Always compare to the previous state.
  • One failure is not an outage. A single dropped packet can flip the state. Require two failures in a row, for example by storing a counter, before you alert.
  • The checker can fail too. If the second machine dies, nothing alerts. Use a second provider or a hosted checker as a backup, and watch the checker’s own heartbeat if you can.
  • Body checks break on redesigns. A changed headline fails your EXPECT string. Pick a stable marker, such as a /health route or a footer string.
  • Secrets in the script. The token sits in a file on disk. Set permissions so only the owner can read it, and do not paste it into logs.
  • Clock and timezone. Timers use the host clock. A wrong time zone does not break OnUnitActiveSec, but it confuses log reading.

Troubleshooting#

SymptomLikely causeFix
curl: (28) Operation timed out after 10001 millisecondsServer slow or unreachableCheck the server, firewall and DNS from the checker
curl: (22) The requested URL returned error: 502Backend behind the proxy is downCheck the app and proxy logs, see fix 502 bad gateway
curl: (60) SSL certificate problem: certificate has expiredExpired certificateRenew it and check the renewal logs
curl: (6) Could not resolve hostDNS problem on the checker or the domainTest with dig from the checker
Script runs but no alert arrivesWrong webhook URL or tokenRun the webhook curl by hand and read the response
Permission denied writing the state fileState directory owned by another userCreate it and set ownership to the user running the script
Timer shows n/a for NEXTTimer not enabled or unit file has an errorRun systemctl status check-site.timer and systemd-analyze verify
Alert on every runState file not writtenFix the path and permissions, then rerun

Quick reference#

bash
curl -fsS --max-time 10 -o /dev/null https://example.com/
echo $?
sudo systemctl enable --now check-site.timer
systemctl list-timers check-site.timer
journalctl -u check-site.service --since "10 minutes ago"

Related post: health checks that pass on a dead container.

Next#

Learn where the logs go in log basics with journald and logrotate.

Try it: Check a URL with curl and read the exit code

Use curl the way the script does and see how the exit code reports success or failure.

practice, nothing runs on your machine

Want a real machine? Free browser labs: Killercoda

Check what you learned4 questions
1What does the -f flag do in curl -fsS?
2Why is --max-time important in a check script?
3What stops the script from alerting every minute during a long outage?
4Which timer setting runs a job 60 seconds after the previous run finished?

Frequently asked questions

How do I check if a website is up with curl?

Run curl -fsS --max-time 10 -o /dev/null https://example.com/. With -f it exits non-zero on HTTP errors, -sS keeps it quiet but shows errors, and --max-time stops it hanging.

Why run the uptime check from a different server?

If the monitored server loses power or network, a check running on it cannot report anything. A second machine also tests DNS, TLS and the network path like a real visitor.

Cron or a systemd timer for monitoring checks?

Either works. Cron is one line and familiar. A systemd timer gives you logs in journalctl, a clear failure state and options like OnUnitActiveSec to run a set time after the last run finished.

How do I stop a monitoring script from sending the same alert every minute?

Store the last known state in a file and send an alert only when the state changes from up to down or back. This turns a stream of failures into one alert and one recovery message.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios