>_ IzzyLab

Hands-on task

This task is step 11 of the course “Running a server”

Write a healthcheck

medium~15 min

Write an executable script /usr/local/bin/healthcheck that takes a URL as an argument, exits with code 0 if the URL responds with HTTP 200, and 1 otherwise. Then set up a cron job (in any user's crontab or as a file in /etc/cron.d/) that runs it against http://localhost:5000/health every minute, appending its output to /var/log/healthcheck.log. The cron daemon isn't running in the sandbox — start it yourself.

What you'll practise:
  • curl http_code
  • exit code
  • cron
  • crontab
  • append >>

Topic breakdown

A two-part task — a check script and the cron job that drives it. The script reports its result via the exit code (0/1), which automation uses to tell whether the service is alive; the response status is easy to grab with curl, which has an option to print only the response code (-w '%{http_code}') and an option to dump the body to /dev/null, while the URL arrives as $1. Periodic execution is set up by cron: a crontab entry with five schedule fields (all asterisks = every minute) plus a command that appends output to the log with the >> operator (doubled, so old content isn't overwritten).

What's checked

  1. healthcheck script is executable
  2. healthcheck returns 0 for a live URL
  3. healthcheck returns 1 for a dead URL
  4. cron runs healthcheck every minute
  5. the cron daemon is running

What it looks like