如何在 CTRL+C-ing docker 撰写时从服务打印到终端(对 SIGINT/SIGTERM 作出反应)?

How to print to terminal from a service (reacting to SIGINT/SIGTERM) when CTRL+C-ing docker compose?

我有一项服务(在该示例中为 python)可以在 SIGINT/SIGTERM.

上打印内容

printer.py:

import signal
import sys
import threading

def runner(stop_event):
    while not stop_event.wait(1):
        print('Hi.', flush=True)

stop_event = threading.Event()

def signal_handler(*_):
    stop_event.set()
    print('Bye.', flush=True)
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)

runner_thread = threading.Thread(target=runner, args=(stop_event,))
runner_thread.start()
runner_thread.join()

当 运行 在终端中正常按 CTRL+C 时,它工作正常,即打印 Bye. 消息:

$ python3 printer.py 
Hi.
Hi.
^CBye.

然而,当 运行 Docker 组合并 CTRL+C-ing 时,Bye. 永远不会显示。

Dockerfile:

FROM python:3.7
ADD printer.py .
CMD [ "python", "printer.py" ]

docker-compose.yml:

version: '2.4'

services:
  printer:
    build:
      context: .
      dockerfile: Dockerfile

终端互动:

$ docker-compose up
Creating network "compose_print_term_default" with the default driver
Creating compose_print_term_printer_1 ... done
Attaching to compose_print_term_printer_1
printer_1  | Hi.
printer_1  | Hi.
^CGracefully stopping... (press Ctrl+C again to force)
Stopping compose_print_term_printer_1 ... done

如何才能使 Bye. 可见?

似乎是 docker compose 的问题,几年前就已为人所知: https://github.com/docker/compose/issues/592