본문 바로가기
잡다구리

docker-compose에서 다른 서비스가 healthy 상태여야 특정 서비스를 기동하여야 할 때

by Growing! 2022. 8. 13.

docker composer를 사용할 때 다른 서비스가 완전히 서비스가 가능한 상태가 된 후에 특정 서비스가 시작되어야 하는 경우가 있다.

이 때 depends_on: <target_service> 을 사용하는데, 해당 서비스가 기동된 것 뿐만 아니라 서비스가 가능한 healthy 상태인 것까지 판단하려면 condition > service_healthy 를 사용해야 한다. 해당 서비스는 healthcheck 설정을 통해 healthy를 판단할 수 있는 방법이 지정되어 있어야 한다.

service_a는 다음과 같은 조건을 만족해야 기동한다고 가정한 예이다.

  • service_b가 기동되어 실제 서비스가 가능한 상태
  • service_c가 기동만 된 상태
services:

  service_1:
    ...
    depends_on:
      service_b:
        condition: service_healthy
      service_c:
        condition: service_started

  service_b:
    ...
    healthcheck:
      test: curl -f https://localhost:8080 || exit 1
      interval: 5s
      timeout: 3s
      retries: 3
      start_period: 20s

  service_c:
    ...

depends_on > condition

(자세한 내용은 https://docs.docker.com/compose/compose-file/#depends_on의 Long syntax 부분을 참고하자.)

depends_on 에서 condition 조건으로 다음과 같이 해당 서비스의 조건을 지정할 수 있다.

  • service_started: 해당 서비스가 start 된 상태여야 한다. condition 을 지정하지 않은 것과 동일한 의미이다.
  • service_healthy: 해당 서비스가 healthy 상태여야 한다. 해당 서비스의 healthcheck 에 지정된 조건을 만족해야 한다.
  • service_completed_successfully: 해당 서비스가 정상 종료된 상태여야 한다.

healthcheck

(자세한 내용은 https://docs.docker.com/compose/compose-file/#healthcheck를 참고하자)

healthcheck 는 해당 서비스의 컨테이너가 healthy 상태인지 체크하는 방법을 정의한다. 이 설정은 Docker image의 HEALTHCHECK 명령을 오버라이드한다.

healthcheck:
  test: ["CMD", "curl", "-f", "http://localhost"]
  interval: 1m30s
  timeout: 10s
  retries: 3
  start_period: 40s

test

test : 컨테이너의 health를 체크하는 명령을 정의한다. 문자열이나 배열로 지정할 수 있다. 배열인 경우, 첫 번째 요소는 반드시 NONE , CMD , CMD-SHELL 중 하나여야 한다. 문자열인 경우에는 CMD-SHELL 다음에 문자열 요소를 하나를 사용하는 것과 동일하다.

명령의 exit code는 컨테이너의 healthy 상태를 판단하는 기준이 되며, 다음의 값을 가질 수 있다.

  • 0 : success - the container is healthy and ready for use
  • 1 : unhealthy - the container is not working correctly
  • 2 : reserved - do not use this exit code

CMD-SHELL 을 사용하는 경우에는 명령어가 컨테이너의 기본 쉘을 사용하여 실행된다(/bin/sh ). 아래의 두 설정은 동일한 의미이다.

test: ["CMD-SHELL", "curl -f http://localhost || exit 1"]
test: curl -f https://localhost || exit 1

curl 호출에 성공하면 exit code가 0 이므로 정상으로 판정되고, 다른 값이면 || 조건이 적용되므로 1 이 되어 비정상으로 판정된다.

interval, timeout, start_period

interval , timeout , start_periodduration 설정을 따른다 - us (microseconds), ms (milliseconds), s (seconds), m (minutes) and h (hours).

start_period 는 컨테이너가 기동되는데 필요한 초기화 시간을 지정한다. 이 기간 내에 test 가 실패한 것은 실패 카운트에 포함하지 않으며, 성공하게 되면 healthy 상태로 판정한다.

참고: curl -f

HTTP 에러가 발생하면 아무런 출력을 하지 않고 실패한다. exit code는 대개 0을 반환한다.

curl --help
Usage: curl [options...] <url>
 -d, --data <data>   HTTP POST data
 -f, --fail          Fail silently (no output at all) on HTTP errors
 ...

참고: exit code 확인하는 방법

$?

어떤 명령을 수행한 후에 $? 를 통해 exit code를 확인할 수 있다.

$ ls; echo $?
0

$ curl -f http://naver.com ; echo $?
0

$ curl -f http://localhost:12345 ; echo $?
7

shell 내장변수:

$$ : 해당 프로세스의 PID값
$? : 가장 최근에 실행한 명령의 종료값
$# : 프로그램에 전달된 인수의 개수
$0 : 명령수행시 명령의 이름을 기억하는 변수값
$n : 전달된 n번째 인수(ex:$1,$2)
$* : 전달된 인수들 전체를 하나의 문자열로 표시함
$@ : 전달된 인수들 전체를 문자열의 목록으로 표시함
$! : 마지막으로 실행된 백그라운드 프로세스 pid값

shell exit code

0 : Successful completion of the command
1 : General unknown error
2 : Misuse of shell command
126 : The command can't execute
127 : Command not found
128 : Invalid exit argument
128+x : Fatal error with Linux signal x
130 : Command terminated with Ctrl-C
255 : Exit status out of range

'잡다구리' 카테고리의 다른 글

reactor: Handle  (0) 2022.08.13
reactor: Synchronous generate  (0) 2022.08.13
reactor: 동기적인 블로킹 호출을 감싸기  (0) 2022.08.13
reactor: publishOn, subscribeOn()  (0) 2022.08.13
스레드 상태 (Thread State)  (0) 2022.08.12
Redis Cluster 구성 테스트  (0) 2022.08.12
redis docker  (0) 2021.08.24
날짜와 시간  (0) 2021.07.31

댓글