3

I have a php project to test healthchecks with three files in it:

index.php

<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
    <h1>Hi from container: <?php echo gethostname(); ?> </h1>
 </body>
</html>

health.php

<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
  <h1>hi</h1>
 </body>
</html>

Dockerfile:

FROM php:8.0-apache
EXPOSE 80
COPY ["./", "/var/www/html/"]
HEALTHCHECK CMD curl --fail http://localhost/health.php exit 1 

I then start the image using docker run -p 8000:80 phpdemo_local

When running the dockerfile it starts up but if i do a docker ps i get the following:

CONTAINER ID   IMAGE                  COMMAND                  CREATED          STATUS                             PORTS     NAMES
e980991ce911   phpdemo_local:latest   "docker-php-entrypoi…"   42 seconds ago   Up 42 seconds (health: starting)   80/tcp    nice_pare

If I open my browser and browse to http://localhost:8000/health.php i get the following response: hi, this is obviously a HTTPStatusCode 200 so my healthcheck should also be passing cause i check for status 200

but for some reason docker ps returns the status "starting" and then eventually the health status changes to "unhealthy".

What am i doing wrong here?

I feel like the HEALTHCHECK url specified is not accessible to the healthchech ?!?

stoic
  • 4,700
  • 13
  • 58
  • 88
  • docker needs a CMD to run at the end. Add `CMD [ "php", "./your-script.php" ]` at the last. Your docker container doesn't even start. It just fires that curl cmd and stops. Health check must be penultimate cmd. – niko May 16 '22 at 13:44
  • 1
    @niko The `php:8.0-alpine` image already has a CMD, so no new one is needed. – Hans Kilian May 16 '22 at 13:48
  • 1
    @niko it does actually run, as i am getting a response from the container when i browse to it in the browser – stoic May 16 '22 at 13:53
  • interval is missing then, `--interval=30s --timeout=3s` it healthcheck fires once and stops. Add above args to healthcheck – niko May 16 '22 at 13:56
  • 1
    @niko what's wrong with the default values of 30s for those two values? – Hans Kilian May 16 '22 at 13:59

1 Answers1

3

You need to have || between the curl command and the exit command, so the exit only is executed if curl fails. Like this

HEALTHCHECK CMD curl --fail http://localhost/health.php || exit 1 
Hans Kilian
  • 18,948
  • 1
  • 26
  • 35
  • This was exactly my problem. Thanx. I take it that i can read up more about your answer by looking at the curl command, or is it specifically related to docker? – stoic May 16 '22 at 14:03
  • 1
    It's a Linux shell thing. It's an 'or' operator, so if the first command is successful (or true), then there's no need to execute the second part because the whole expression will be true no matter if the second part succeeds or not. It's more common to see the `&&` operator used to chain commands together, but it's the same principle. – Hans Kilian May 16 '22 at 14:09