PHP HealthCheck

As part of my migration to docker, I decided I wanted to make all of my containers use health checks. The end solution is pretty straight forward, but it took a bit to sort out how to make things happen.

I wanted my health check to actually ensure that the php-fpm was running, and that php scripts were processing correctly, and I didn’t want anything else to be tested. A lot of examples were using curl and expecting the reverse proxy and php to be in the same container. But that sort of check could fail because of an issue with the reverse proxy.

So I found an example of using the cgi-fcgi command on Max Chadwick’s Blog, which showed me how to create the health check. But the next issue is that the php fpm alpine image doesn’t have that package installed.

The solution, was to create a Dockerfile which made the change needed to my base image, based on this answer I found StackOverflow:

FROM php:8.3-fpm-alpine

RUN apk add fcgi

In my compose.yaml, I just had to update to use the image indirectly, as to utilize the new Dockerfile:

-    image: php:8.3-fpm-alpine
+    build: .
+    healthcheck:
+      test: SCRIPT_FILENAME=/ping.php REQUEST_METHOD=GET cgi-fcgi -bind -connect localhost:9000 | grep 'pong' || exit 1
+      interval: 60s
+      retries: 3
+      start_period: 10s
+      timeout: 5s
+      - ./ping.php:/ping.php:ro # read-only

And of course, I needed the php script to run:

<?php echo implode('', ['p', 'o', 'n', 'g']);

The nice thing about my ping/pong is that if fpm ever failed to process the PHP, and return the file content, that would make the health check fail. And it doesn’t run the risk of leaking any data.