{
  "$type": "site.standard.document",
  "canonicalUrl": "https://rednafi.com/misc/health-check-a-server-with-nohup/",
  "description": "Run background health checks in CI with nohup and ampersand. Test server readiness with retry loops and automatic cleanup on success or failure.",
  "path": "/misc/health-check-a-server-with-nohup/",
  "publishedAt": "2022-04-18T00:00:00.000Z",
  "site": "at://did:plc:fgtm2c26vfcj74rfmeggbyqj/site.standard.publication/3mnl6f7ob462z",
  "tags": [
    "Shell",
    "Unix",
    "TIL",
    "DevOps"
  ],
  "textContent": "While working on a project with [EdgeDB] and [FastAPI], I wanted to perform health checks\nagainst the FastAPI server in the GitHub CI. This would notify me about the working state of\nthe application. The idea is to:\n\n- Run the server in the background.\n- Run the commands against the server that'll denote that the app is in a working state.\n- Perform cleanup.\n- Exit with code 0 if the check is successful, else exit with code 1.\n\nThe following shell script demonstrates a similar workflow with a Python HTTP server. This\nscript:\n\n- Runs a Python web server in the background.\n- Makes an HTTP request against the server and checks if it returns HTTP 200 (OK). If the\n  request fails or the server isn't ready then waits for a second and makes the request\n  again, and keeps retrying for the next 20 times before giving up.\n- Performs cleanups and kills the Python processes.\n- Exit with code 0 if the request is successful, else exit with code 1.\n\nThe nohup before the python3 -m http.server 5000 makes sure that the SIGHUP signal\ncan't reach the server and shut down the process. The ampersand & after the command runs\nthe process in the background. Afterward, the script starts making requests to the\nhttp://localhost:5000/ URL in a loop. If the server returns HTTP 200, the health check is\nconsidered successful. This will break the loop and the script will be terminated with\nexit 0 status. If the server doesn't return HTTP 200 or isn't ready yet, the script will\nkeep retrying 20 times with a 1 second interval between each subsequent request before\ngiving up. A failed health check will cause the script to terminate with exit 1 status.\n\nFurther reading\n\n- [Difference between nohup and ampersand]\n\n\n\n\n[edgedb]:\n    https://www.edgedb.com/\n\n[fastapi]:\n    https://fastapi.tiangolo.com/\n\n[difference between nohup and ampersand]:\n    https://stackoverflow.com/questions/15595374/whats-the-difference-between-nohup-and-ampersand",
  "title": "Health check a server with 'nohup $(cmd) &'"
}