代码之家  ›  专栏  ›  技术社区  ›  Tobias Hermann

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

  •  0
  • Tobias Hermann  · 技术社区  · 5 年前

    我有一个服务(在那个例子中是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 compose并按住CTRL+C键时, 再见 从来没有显示过。

    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
    

    怎样做才能使 再见 看得见的

    0 回复  |  直到 5 年前
        1
  •  0
  •   Tobias Hermann    5 年前

    这似乎是docker compose的一个问题,已经知道了几年: https://github.com/docker/compose/issues/592