Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should i use grep in docker-compose healthcheck?

I'm trying to add healthcheck for my docker app by grep the curl result. When i run into docker container:

curl -sS http://nginx | grep -c works > /dev/null 
echo $?

I getting 0 and everything seems fine, but if I'm trying to add it into docker-compose

version: "3.8"

services:
  php:
    build: .
    volumes:
     - ./www:/var/www
    healthcheck:
     test: ["CMD", "curl", "-sS", "http://nginx | grep", "-c", "works > /dev/null"]
     interval: 5s
     timeout: 5s
     retries: 5
  nginx:
    image: "nginx:latest"
    ports:
     - "8080:80"
    volumes:
     - ./nginx:/etc/nginx/conf.d
     - ./www:/var/www
    links:
     - php

and check it by docker-compose ps it has status "unhealthy". What am I doing wrong?

like image 242
kravzo Avatar asked Sep 14 '25 06:09

kravzo


1 Answers

There are two problems here:

  1. You split your arguments in a weird way - "http://nginx | grep" and "works > /dev/null" don't make much sense and will be passed literally to curl

  2. You are using a format in test which does not call the shell - as such, shell fetures like | and > won't work since they need to be interpreted by your shell. You need to either pass test as a string, or use the CMD-SHELL form:

   healthcheck:
     test: curl -sS http://nginx | grep -c works > /dev/null
     interval: 5s
     timeout: 5s
     retries: 5

Or:

    healthcheck:
     test: ["CMD-SHELL", "curl -sS http://nginx | grep -c works > /dev/null"]
     interval: 5s
     timeout: 5s
     retries: 5

For more information on healthcheck, you can read about it in the compose file reference.

like image 147
Leonardo Dagnino Avatar answered Sep 16 '25 18:09

Leonardo Dagnino